qcore.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. # Copyright 2007 Matt Chaput. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are met:
  5. #
  6. # 1. Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. #
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
  14. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. #
  24. # The views and conclusions contained in the software and documentation are
  25. # those of the authors and should not be interpreted as representing official
  26. # policies, either expressed or implied, of Matt Chaput.
  27. from __future__ import division
  28. import copy
  29. from array import array
  30. from whoosh import matching
  31. from whoosh.compat import u
  32. from whoosh.reading import TermNotFound
  33. from whoosh.compat import methodcaller
  34. # Exceptions
  35. class QueryError(Exception):
  36. """Error encountered while running a query.
  37. """
  38. pass
  39. # Functions
  40. def error_query(msg, q=None):
  41. """Returns the query in the second argument (or a :class:`NullQuery` if the
  42. second argument is not given) with its ``error`` attribute set to
  43. ``msg``.
  44. """
  45. if q is None:
  46. q = _NullQuery()
  47. q.error = msg
  48. return q
  49. def token_lists(q, phrases=True):
  50. """Returns the terms in the query tree, with the query hierarchy
  51. represented as nested lists.
  52. """
  53. if q.is_leaf():
  54. from whoosh.query import Phrase
  55. if phrases or not isinstance(q, Phrase):
  56. return list(q.tokens())
  57. else:
  58. ls = []
  59. for qq in q.children():
  60. t = token_lists(qq, phrases=phrases)
  61. if len(t) == 1:
  62. t = t[0]
  63. if t:
  64. ls.append(t)
  65. return ls
  66. # Utility classes
  67. class Lowest(object):
  68. """A value that is always compares lower than any other object except
  69. itself.
  70. """
  71. def __cmp__(self, other):
  72. if other.__class__ is Lowest:
  73. return 0
  74. return -1
  75. def __eq__(self, other):
  76. return self.__class__ is type(other)
  77. def __lt__(self, other):
  78. return type(other) is not self.__class__
  79. def __ne__(self, other):
  80. return not self.__eq__(other)
  81. def __gt__(self, other):
  82. return not (self.__lt__(other) or self.__eq__(other))
  83. def __le__(self, other):
  84. return self.__eq__(other) or self.__lt__(other)
  85. def __ge__(self, other):
  86. return self.__eq__(other) or self.__gt__(other)
  87. class Highest(object):
  88. """A value that is always compares higher than any other object except
  89. itself.
  90. """
  91. def __cmp__(self, other):
  92. if other.__class__ is Highest:
  93. return 0
  94. return 1
  95. def __eq__(self, other):
  96. return self.__class__ is type(other)
  97. def __lt__(self, other):
  98. return type(other) is self.__class__
  99. def __ne__(self, other):
  100. return not self.__eq__(other)
  101. def __gt__(self, other):
  102. return not (self.__lt__(other) or self.__eq__(other))
  103. def __le__(self, other):
  104. return self.__eq__(other) or self.__lt__(other)
  105. def __ge__(self, other):
  106. return self.__eq__(other) or self.__gt__(other)
  107. Lowest = Lowest()
  108. Highest = Highest()
  109. # Base classes
  110. class Query(object):
  111. """Abstract base class for all queries.
  112. Note that this base class implements __or__, __and__, and __sub__ to allow
  113. slightly more convenient composition of query objects::
  114. >>> Term("content", u"a") | Term("content", u"b")
  115. Or([Term("content", u"a"), Term("content", u"b")])
  116. >>> Term("content", u"a") & Term("content", u"b")
  117. And([Term("content", u"a"), Term("content", u"b")])
  118. >>> Term("content", u"a") - Term("content", u"b")
  119. And([Term("content", u"a"), Not(Term("content", u"b"))])
  120. """
  121. # For queries produced by the query parser, record where in the user
  122. # query this object originated
  123. startchar = endchar = None
  124. # For queries produced by the query parser, records an error that resulted
  125. # in this query
  126. error = None
  127. def __unicode__(self):
  128. raise NotImplementedError(self.__class__.__name__)
  129. def __getitem__(self, item):
  130. raise NotImplementedError
  131. def __or__(self, query):
  132. """Allows you to use | between query objects to wrap them in an Or
  133. query.
  134. """
  135. from whoosh.query import Or
  136. return Or([self, query]).normalize()
  137. def __and__(self, query):
  138. """Allows you to use & between query objects to wrap them in an And
  139. query.
  140. """
  141. from whoosh.query import And
  142. return And([self, query]).normalize()
  143. def __sub__(self, query):
  144. """Allows you to use - between query objects to add the right-hand
  145. query as a "NOT" query.
  146. """
  147. from whoosh.query import And, Not
  148. return And([self, Not(query)]).normalize()
  149. def __hash__(self):
  150. raise NotImplementedError
  151. def __ne__(self, other):
  152. return not self.__eq__(other)
  153. def is_leaf(self):
  154. """Returns True if this is a leaf node in the query tree, or False if
  155. this query has sub-queries.
  156. """
  157. return True
  158. def children(self):
  159. """Returns an iterator of the subqueries of this object.
  160. """
  161. return iter([])
  162. def is_range(self):
  163. """Returns True if this object searches for values within a range.
  164. """
  165. return False
  166. def has_terms(self):
  167. """Returns True if this specific object represents a search for a
  168. specific term (as opposed to a pattern, as in Wildcard and Prefix) or
  169. terms (i.e., whether the ``replace()`` method does something
  170. meaningful on this instance).
  171. """
  172. return False
  173. def needs_spans(self):
  174. for child in self.children():
  175. if child.needs_spans():
  176. return True
  177. return False
  178. def apply(self, fn):
  179. """If this query has children, calls the given function on each child
  180. and returns a new copy of this node with the new children returned by
  181. the function. If this is a leaf node, simply returns this object.
  182. This is useful for writing functions that transform a query tree. For
  183. example, this function changes all Term objects in a query tree into
  184. Variations objects::
  185. def term2var(q):
  186. if isinstance(q, Term):
  187. return Variations(q.fieldname, q.text)
  188. else:
  189. return q.apply(term2var)
  190. q = And([Term("f", "alfa"),
  191. Or([Term("f", "bravo"),
  192. Not(Term("f", "charlie"))])])
  193. q = term2var(q)
  194. Note that this method does not automatically create copies of nodes.
  195. To avoid modifying the original tree, your function should call the
  196. :meth:`Query.copy` method on nodes before changing their attributes.
  197. """
  198. return self
  199. def accept(self, fn):
  200. """Applies the given function to this query's subqueries (if any) and
  201. then to this query itself::
  202. def boost_phrases(q):
  203. if isintance(q, Phrase):
  204. q.boost *= 2.0
  205. return q
  206. myquery = myquery.accept(boost_phrases)
  207. This method automatically creates copies of the nodes in the original
  208. tree before passing them to your function, so your function can change
  209. attributes on nodes without altering the original tree.
  210. This method is less flexible than using :meth:`Query.apply` (in fact
  211. it's implemented using that method) but is often more straightforward.
  212. """
  213. def fn_wrapper(q):
  214. q = q.apply(fn_wrapper)
  215. return fn(q)
  216. return fn_wrapper(self)
  217. def replace(self, fieldname, oldtext, newtext):
  218. """Returns a copy of this query with oldtext replaced by newtext (if
  219. oldtext was anywhere in this query).
  220. Note that this returns a *new* query with the given text replaced. It
  221. *does not* modify the original query "in place".
  222. """
  223. # The default implementation uses the apply method to "pass down" the
  224. # replace() method call
  225. if self.is_leaf():
  226. return copy.copy(self)
  227. else:
  228. return self.apply(methodcaller("replace", fieldname, oldtext,
  229. newtext))
  230. def copy(self):
  231. """Deprecated, just use ``copy.deepcopy``.
  232. """
  233. return copy.deepcopy(self)
  234. def all_terms(self, phrases=True):
  235. """Returns a set of all terms in this query tree.
  236. This method exists for backwards-compatibility. Use iter_all_terms()
  237. instead.
  238. :param phrases: Whether to add words found in Phrase queries.
  239. :rtype: set
  240. """
  241. return set(self.iter_all_terms(phrases=phrases))
  242. def terms(self, phrases=False):
  243. """Yields zero or more (fieldname, text) pairs queried by this object.
  244. You can check whether a query object targets specific terms before you
  245. call this method using :meth:`Query.has_terms`.
  246. To get all terms in a query tree, use :meth:`Query.iter_all_terms`.
  247. """
  248. return iter(())
  249. def expanded_terms(self, ixreader, phrases=True):
  250. return self.terms(phrases=phrases)
  251. def existing_terms(self, ixreader, phrases=True, expand=False, fieldname=None):
  252. """Returns a set of all byteterms in this query tree that exist in
  253. the given ixreader.
  254. :param ixreader: A :class:`whoosh.reading.IndexReader` object.
  255. :param phrases: Whether to add words found in Phrase queries.
  256. :param expand: If True, queries that match multiple terms
  257. will return all matching expansions.
  258. :rtype: set
  259. """
  260. schema = ixreader.schema
  261. termset = set()
  262. for q in self.leaves():
  263. if fieldname and fieldname != q.field():
  264. continue
  265. if expand:
  266. terms = q.expanded_terms(ixreader, phrases=phrases)
  267. else:
  268. terms = q.terms(phrases=phrases)
  269. for fieldname, text in terms:
  270. if (fieldname, text) in termset:
  271. continue
  272. if fieldname in schema:
  273. field = schema[fieldname]
  274. try:
  275. btext = field.to_bytes(text)
  276. except ValueError:
  277. continue
  278. if (fieldname, btext) in ixreader:
  279. termset.add((fieldname, btext))
  280. return termset
  281. def leaves(self):
  282. """Returns an iterator of all the leaf queries in this query tree as a
  283. flat series.
  284. """
  285. if self.is_leaf():
  286. yield self
  287. else:
  288. for q in self.children():
  289. for qq in q.leaves():
  290. yield qq
  291. def iter_all_terms(self, phrases=True):
  292. """Returns an iterator of (fieldname, text) pairs for all terms in
  293. this query tree.
  294. >>> qp = qparser.QueryParser("text", myindex.schema)
  295. >>> q = myparser.parse("alfa bravo title:charlie")
  296. >>> # List the terms in a query
  297. >>> list(q.iter_all_terms())
  298. [("text", "alfa"), ("text", "bravo"), ("title", "charlie")]
  299. >>> # Get a set of all terms in the query that don't exist in the index
  300. >>> r = myindex.reader()
  301. >>> missing = set(t for t in q.iter_all_terms() if t not in r)
  302. set([("text", "alfa"), ("title", "charlie")])
  303. >>> # All terms in the query that occur in fewer than 5 documents in
  304. >>> # the index
  305. >>> [t for t in q.iter_all_terms() if r.doc_frequency(t[0], t[1]) < 5]
  306. [("title", "charlie")]
  307. :param phrases: Whether to add words found in Phrase queries.
  308. """
  309. for q in self.leaves():
  310. if q.has_terms():
  311. for t in q.terms(phrases=phrases):
  312. yield t
  313. def all_tokens(self, boost=1.0):
  314. """Returns an iterator of :class:`analysis.Token` objects corresponding
  315. to all terms in this query tree. The Token objects will have the
  316. ``fieldname``, ``text``, and ``boost`` attributes set. If the query
  317. was built by the query parser, they Token objects will also have
  318. ``startchar`` and ``endchar`` attributes indexing into the original
  319. user query.
  320. """
  321. if self.is_leaf():
  322. for token in self.tokens(boost):
  323. yield token
  324. else:
  325. boost *= self.boost if hasattr(self, "boost") else 1.0
  326. for child in self.children():
  327. for token in child.all_tokens(boost):
  328. yield token
  329. def tokens(self, boost=1.0, exreader=None):
  330. """Yields zero or more :class:`analysis.Token` objects corresponding to
  331. the terms searched for by this query object. You can check whether a
  332. query object targets specific terms before you call this method using
  333. :meth:`Query.has_terms`.
  334. The Token objects will have the ``fieldname``, ``text``, and ``boost``
  335. attributes set. If the query was built by the query parser, they Token
  336. objects will also have ``startchar`` and ``endchar`` attributes
  337. indexing into the original user query.
  338. To get all tokens for a query tree, use :meth:`Query.all_tokens`.
  339. :param exreader: a reader to use to expand multiterm queries such as
  340. prefixes and wildcards. The default is None meaning do not expand.
  341. """
  342. return iter(())
  343. def requires(self):
  344. """Returns a set of queries that are *known* to be required to match
  345. for the entire query to match. Note that other queries might also turn
  346. out to be required but not be determinable by examining the static
  347. query.
  348. >>> a = Term("f", u"a")
  349. >>> b = Term("f", u"b")
  350. >>> And([a, b]).requires()
  351. set([Term("f", u"a"), Term("f", u"b")])
  352. >>> Or([a, b]).requires()
  353. set([])
  354. >>> AndMaybe(a, b).requires()
  355. set([Term("f", u"a")])
  356. >>> a.requires()
  357. set([Term("f", u"a")])
  358. """
  359. # Subclasses should implement the _add_required_to(qset) method
  360. return set([self])
  361. def field(self):
  362. """Returns the field this query matches in, or None if this query does
  363. not match in a single field.
  364. """
  365. return self.fieldname
  366. def with_boost(self, boost):
  367. """Returns a COPY of this query with the boost set to the given value.
  368. If a query type does not accept a boost itself, it will try to pass the
  369. boost on to its children, if any.
  370. """
  371. q = self.copy()
  372. q.boost = boost
  373. return q
  374. def estimate_size(self, ixreader):
  375. """Returns an estimate of how many documents this query could
  376. potentially match (for example, the estimated size of a simple term
  377. query is the document frequency of the term). It is permissible to
  378. overestimate, but not to underestimate.
  379. """
  380. raise NotImplementedError
  381. def estimate_min_size(self, ixreader):
  382. """Returns an estimate of the minimum number of documents this query
  383. could potentially match.
  384. """
  385. return self.estimate_size(ixreader)
  386. def matcher(self, searcher, context=None):
  387. """Returns a :class:`~whoosh.matching.Matcher` object you can use to
  388. retrieve documents and scores matching this query.
  389. :rtype: :class:`whoosh.matching.Matcher`
  390. """
  391. raise NotImplementedError
  392. def docs(self, searcher):
  393. """Returns an iterator of docnums matching this query.
  394. >>> with my_index.searcher() as searcher:
  395. ... list(my_query.docs(searcher))
  396. [10, 34, 78, 103]
  397. :param searcher: A :class:`whoosh.searching.Searcher` object.
  398. """
  399. try:
  400. context = searcher.boolean_context()
  401. return self.matcher(searcher, context).all_ids()
  402. except TermNotFound:
  403. return iter([])
  404. def deletion_docs(self, searcher):
  405. """Returns an iterator of docnums matching this query for the purpose
  406. of deletion. The :meth:`~whoosh.writing.IndexWriter.delete_by_query`
  407. method will use this method when deciding what documents to delete,
  408. allowing special queries (e.g. nested queries) to override what
  409. documents are deleted. The default implementation just forwards to
  410. :meth:`Query.docs`.
  411. """
  412. return self.docs(searcher)
  413. def normalize(self):
  414. """Returns a recursively "normalized" form of this query. The
  415. normalized form removes redundancy and empty queries. This is called
  416. automatically on query trees created by the query parser, but you may
  417. want to call it yourself if you're writing your own parser or building
  418. your own queries.
  419. >>> q = And([And([Term("f", u"a"),
  420. ... Term("f", u"b")]),
  421. ... Term("f", u"c"), Or([])])
  422. >>> q.normalize()
  423. And([Term("f", u"a"), Term("f", u"b"), Term("f", u"c")])
  424. Note that this returns a *new, normalized* query. It *does not* modify
  425. the original query "in place".
  426. """
  427. return self
  428. def simplify(self, ixreader):
  429. """Returns a recursively simplified form of this query, where
  430. "second-order" queries (such as Prefix and Variations) are re-written
  431. into lower-level queries (such as Term and Or).
  432. """
  433. return self
  434. # Null query
  435. class _NullQuery(Query):
  436. "Represents a query that won't match anything."
  437. boost = 1.0
  438. def __init__(self):
  439. self.error = None
  440. def __unicode__(self):
  441. return u("<_NullQuery>")
  442. def __call__(self):
  443. return self
  444. def __repr__(self):
  445. return "<%s>" % (self.__class__.__name__)
  446. def __eq__(self, other):
  447. return isinstance(other, _NullQuery)
  448. def __ne__(self, other):
  449. return not self.__eq__(other)
  450. def __hash__(self):
  451. return id(self)
  452. def __copy__(self):
  453. return self
  454. def __deepcopy__(self, memo):
  455. return self
  456. def field(self):
  457. return None
  458. def estimate_size(self, ixreader):
  459. return 0
  460. def normalize(self):
  461. return self
  462. def simplify(self, ixreader):
  463. return self
  464. def docs(self, searcher):
  465. return []
  466. def matcher(self, searcher, context=None):
  467. return matching.NullMatcher()
  468. NullQuery = _NullQuery()
  469. # Every
  470. class Every(Query):
  471. """A query that matches every document containing any term in a given
  472. field. If you don't specify a field, the query matches every document.
  473. >>> # Match any documents with something in the "path" field
  474. >>> q = Every("path")
  475. >>> # Matcher every document
  476. >>> q = Every()
  477. The unfielded form (matching every document) is efficient.
  478. The fielded is more efficient than a prefix query with an empty prefix or a
  479. '*' wildcard, but it can still be very slow on large indexes. It requires
  480. the searcher to read the full posting list of every term in the given
  481. field.
  482. Instead of using this query it is much more efficient when you create the
  483. index to include a single term that appears in all documents that have the
  484. field you want to match.
  485. For example, instead of this::
  486. # Match all documents that have something in the "path" field
  487. q = Every("path")
  488. Do this when indexing::
  489. # Add an extra field that indicates whether a document has a path
  490. schema = fields.Schema(path=fields.ID, has_path=fields.ID)
  491. # When indexing, set the "has_path" field based on whether the document
  492. # has anything in the "path" field
  493. writer.add_document(text=text_value1)
  494. writer.add_document(text=text_value2, path=path_value2, has_path="t")
  495. Then to find all documents with a path::
  496. q = Term("has_path", "t")
  497. """
  498. def __init__(self, fieldname=None, boost=1.0):
  499. """
  500. :param fieldname: the name of the field to match, or ``None`` or ``*``
  501. to match all documents.
  502. """
  503. if not fieldname or fieldname == "*":
  504. fieldname = None
  505. self.fieldname = fieldname
  506. self.boost = boost
  507. def __repr__(self):
  508. return "%s(%r, boost=%s)" % (self.__class__.__name__, self.fieldname,
  509. self.boost)
  510. def __eq__(self, other):
  511. return (other and self.__class__ is other.__class__
  512. and self.fieldname == other.fieldname
  513. and self.boost == other.boost)
  514. def __unicode__(self):
  515. return u("%s:*") % self.fieldname
  516. __str__ = __unicode__
  517. def __hash__(self):
  518. return hash(self.fieldname)
  519. def estimate_size(self, ixreader):
  520. return ixreader.doc_count()
  521. def matcher(self, searcher, context=None):
  522. fieldname = self.fieldname
  523. reader = searcher.reader()
  524. if fieldname in (None, "", "*"):
  525. # This takes into account deletions
  526. doclist = array("I", reader.all_doc_ids())
  527. else:
  528. # This is a hacky hack, but just create an in-memory set of all the
  529. # document numbers of every term in the field. This is SLOOOW for
  530. # large indexes
  531. doclist = set()
  532. for text in searcher.lexicon(fieldname):
  533. pr = searcher.postings(fieldname, text)
  534. doclist.update(pr.all_ids())
  535. doclist = sorted(doclist)
  536. return matching.ListMatcher(doclist, all_weights=self.boost)