예제 #1
0
class IndexSearch(QueryParser):
    def __init__(self, index='test.ind'):
        super(IndexSearch, self).__init__()
        self.add_operator('_and_', 'binary', 1, self.__and)
        self.index_file = index
        self.index = Index(index)

    def __and(self, left, right):
        return left.value & right.value

    def _split_query(self, query):
        result = []
        for statement in query.split():
            result.append(statement)
            result.append('_and_')
        return result[:-1]

    def _get_value(self, statement):
        if type(statement) == str:
            term = self.index.get_term(statement)
            return QueryNode(term.name, term)
        else:
            return statement

    def calc_node(self, node):
        if not self._is_operator(node.key):
            return node.value
        elif self._is_binary_operator(node.key):
            return self.binary_ops[node.key](node.left, node.right)
        elif self._is_unary_operator(node.key):
            return self.unary_ops[node.key](node.left, node.right)
        else:
            raise QueryParseError("Unknown statement type %s", node.key)

    def calc(self):
        self.log.info("Calculating expression tree")
        for node in self.traverse():
            node.value = self.calc_node(node)
        self.log.info("Found %s documents", len(self.root.value))
        return self.root

    def search(self, query):
        result = []
        try:
            self.parse(query)
            result = self.calc()
            return result
        except QueryParseError as e:
            self.log.exception("Exception while parsing query: %s", e)
            raise e
        except Exception as e:
            self.log.exception("Unknown exception while searching: %s", e)
            raise e