PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/src/whoosh/fields.py

https://bitbucket.org/rayleyva/whoosh
Python | 1372 lines | 1271 code | 30 blank | 71 comment | 21 complexity | 75fcc6e1a2ebc0a0be189c5deda0023c MD5 | raw file
Possible License(s): Apache-2.0
  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. """ Contains functions and classes related to fields.
  28. """
  29. import datetime, fnmatch, re, struct, sys
  30. from array import array
  31. from decimal import Decimal
  32. from whoosh import analysis, columns, formats
  33. from whoosh.compat import u, b, PY3
  34. from whoosh.compat import with_metaclass
  35. from whoosh.compat import itervalues, xrange
  36. from whoosh.compat import bytes_type, string_type, integer_types, text_type
  37. from whoosh.system import emptybytes
  38. from whoosh.system import pack_byte, unpack_byte
  39. from whoosh.util.numeric import to_sortable, from_sortable
  40. from whoosh.util.numeric import typecode_max, NaN
  41. from whoosh.util.text import utf8encode, utf8decode
  42. from whoosh.util.times import datetime_to_long, long_to_datetime
  43. # Exceptions
  44. class FieldConfigurationError(Exception):
  45. pass
  46. class UnknownFieldError(Exception):
  47. pass
  48. # Field Types
  49. class FieldType(object):
  50. """Represents a field configuration.
  51. The FieldType object supports the following attributes:
  52. * format (formats.Format): the storage format for the field's contents.
  53. * analyzer (analysis.Analyzer): the analyzer to use to turn text into
  54. terms.
  55. * vector (formats.Format): the storage format for the field's vectors
  56. (forward index), or None if the field should not store vectors.
  57. * scorable (boolean): whether searches against this field may be scored.
  58. This controls whether the index stores per-document field lengths for
  59. this field.
  60. * stored (boolean): whether the content of this field is stored for each
  61. document. For example, in addition to indexing the title of a document,
  62. you usually want to store the title so it can be presented as part of
  63. the search results.
  64. * unique (boolean): whether this field's value is unique to each document.
  65. For example, 'path' or 'ID'. IndexWriter.update_document() will use
  66. fields marked as 'unique' to find the previous version of a document
  67. being updated.
  68. * multitoken_query is a string indicating what kind of query to use when
  69. a "word" in a user query parses into multiple tokens. The string is
  70. interpreted by the query parser. The strings understood by the default
  71. query parser are "first" (use first token only), "and" (join the tokens
  72. with an AND query), "or" (join the tokens with OR), "phrase" (join
  73. the tokens with a phrase query), and "default" (use the query parser's
  74. default join type).
  75. The constructor for the base field type simply lets you supply your own
  76. configured field format, vector format, and scorable and stored values.
  77. Subclasses may configure some or all of this for you.
  78. """
  79. analyzer = format = vector = scorable = stored = unique = None
  80. indexed = True
  81. multitoken_query = "default"
  82. sortable_typecode = None
  83. spelling = False
  84. column_type = None
  85. def __init__(self, format, analyzer, vector=None, scorable=False,
  86. stored=False, unique=False, multitoken_query="default",
  87. sortable=False):
  88. assert isinstance(format, formats.Format)
  89. self.format = format
  90. self.analyzer = analyzer
  91. self.vector = vector
  92. self.scorable = scorable
  93. self.stored = stored
  94. self.unique = unique
  95. self.multitoken_query = multitoken_query
  96. self.set_sortable(sortable)
  97. def __repr__(self):
  98. temp = "%s(format=%r, vector=%r, scorable=%s, stored=%s, unique=%s)"
  99. return temp % (self.__class__.__name__, self.format, self.vector,
  100. self.scorable, self.stored, self.unique)
  101. def __eq__(self, other):
  102. return all((isinstance(other, FieldType),
  103. (self.format == other.format),
  104. (self.vector == other.vector),
  105. (self.scorable == other.scorable),
  106. (self.stored == other.stored),
  107. (self.unique == other.unique),
  108. (self.column_type == other.column_type)))
  109. def __ne__(self, other):
  110. return not(self.__eq__(other))
  111. # Column methods
  112. def set_sortable(self, sortable):
  113. if sortable:
  114. if isinstance(sortable, columns.Column):
  115. self.column_type = sortable
  116. else:
  117. self.column_type = self.default_column()
  118. else:
  119. self.column_type = None
  120. def default_column(self):
  121. return columns.VarBytesColumn()
  122. # Methods for converting input into indexing information
  123. def index(self, value, **kwargs):
  124. """Returns an iterator of (btext, frequency, weight, encoded_value)
  125. tuples for each unique word in the input value.
  126. The default implementation uses the ``analyzer`` attribute to tokenize
  127. the value into strings, then encodes them into bytes using UTF-8.
  128. """
  129. if not self.format:
  130. raise Exception("%s field %r cannot index without a format"
  131. % (self.__class__.__name__, self))
  132. if not isinstance(value, (text_type, list, tuple)):
  133. raise ValueError("%r is not unicode or sequence" % value)
  134. assert isinstance(self.format, formats.Format)
  135. if "mode" not in kwargs:
  136. kwargs["mode"] = "index"
  137. word_values = self.format.word_values
  138. ana = self.analyzer
  139. for tstring, freq, wt, vbytes in word_values(value, ana, **kwargs):
  140. yield (utf8encode(tstring)[0], freq, wt, vbytes)
  141. def process_text(self, qstring, mode='', **kwargs):
  142. """Analyzes the given string and returns an iterator of token texts.
  143. >>> field = fields.TEXT()
  144. >>> list(field.process_text("The ides of March"))
  145. ["ides", "march"]
  146. """
  147. if not self.format:
  148. raise Exception("%s field has no format" % self)
  149. return (t.text for t in self.tokenize(qstring, mode=mode, **kwargs))
  150. def tokenize(self, value, **kwargs):
  151. """Analyzes the given string and returns an iterator of Token objects
  152. (note: for performance reasons, actually the same token yielded over
  153. and over with different attributes).
  154. """
  155. if not self.analyzer:
  156. raise Exception("%s field has no analyzer" % self.__class__)
  157. return self.analyzer(value, **kwargs)
  158. def to_bytes(self, value):
  159. """Returns a bytes representation of the given value, appropriate to be
  160. written to disk. The default implementation assumes a unicode value and
  161. encodes it using UTF-8.
  162. """
  163. if isinstance(value, (list, tuple)):
  164. value = value[0]
  165. if not isinstance(value, bytes_type):
  166. value = utf8encode(value)[0]
  167. return value
  168. def to_column_value(self, value):
  169. """Returns an object suitable to be inserted into the document values
  170. column for this field. The default implementation simply calls
  171. ``self.to_bytes(value)``.
  172. """
  173. return self.to_bytes(value)
  174. def from_column_value(self, value):
  175. return self.from_bytes(value)
  176. def from_bytes(self, bs):
  177. return utf8decode(bs)[0]
  178. # Methods related to query parsing
  179. def self_parsing(self):
  180. """Subclasses should override this method to return True if they want
  181. the query parser to call the field's ``parse_query()`` method instead
  182. of running the analyzer on text in this field. This is useful where
  183. the field needs full control over how queries are interpreted, such
  184. as in the numeric field type.
  185. """
  186. return False
  187. def parse_query(self, fieldname, qstring, boost=1.0):
  188. """When ``self_parsing()`` returns True, the query parser will call
  189. this method to parse basic query text.
  190. """
  191. raise NotImplementedError(self.__class__.__name__)
  192. def parse_range(self, fieldname, start, end, startexcl, endexcl,
  193. boost=1.0):
  194. """When ``self_parsing()`` returns True, the query parser will call
  195. this method to parse range query text. If this method returns None
  196. instead of a query object, the parser will fall back to parsing the
  197. start and end terms using process_text().
  198. """
  199. return None
  200. # Methods related to sortings
  201. def sortable_terms(self, ixreader, fieldname):
  202. """Returns an iterator of the "sortable" tokens in the given reader and
  203. field. These values can be used for sorting. The default implementation
  204. simply returns all tokens in the field.
  205. This can be overridden by field types such as NUMERIC where some values
  206. in a field are not useful for sorting.
  207. """
  208. return ixreader.lexicon(fieldname)
  209. # Methods related to spelling
  210. def separate_spelling(self):
  211. """Returns True if this field requires special handling of the words
  212. that go into the field's word graph.
  213. The default behavior is to return True if the field is "spelled" but
  214. not indexed, or if the field is indexed but the analyzer has
  215. morphological transformations (e.g. stemming). Exotic field types may
  216. need to override this behavior.
  217. This method should return False if the field does not support spelling
  218. (i.e. the ``spelling`` attribute is False).
  219. """
  220. return self.spelling and self.analyzer.has_morph()
  221. def spellable_words(self, value):
  222. """Returns an iterator of each unique word (in sorted order) in the
  223. input value, suitable for inclusion in the field's word graph.
  224. The default behavior is to call the field analyzer with the keyword
  225. argument ``no_morph=True``, which should make the analyzer skip any
  226. morphological transformation filters (e.g. stemming) to preserve the
  227. original form of the words. Excotic field types may need to override
  228. this behavior.
  229. """
  230. wordset = sorted(set(token.text for token
  231. in self.analyzer(value, no_morph=True)))
  232. return iter(wordset)
  233. def has_morph(self):
  234. """Returns True if this field by default performs morphological
  235. transformations on its terms, e.g. stemming.
  236. """
  237. if self.analyzer:
  238. return self.analyzer.has_morph()
  239. else:
  240. return False
  241. # Methods related to the posting/vector formats
  242. def supports(self, name):
  243. """Returns True if the underlying format supports the given posting
  244. value type.
  245. >>> field = TEXT()
  246. >>> field.supports("positions")
  247. True
  248. >>> field.supports("characters")
  249. False
  250. """
  251. return self.format.supports(name)
  252. def clean(self):
  253. """Clears any cached information in the field and any child objects.
  254. """
  255. if self.format and hasattr(self.format, "clean"):
  256. self.format.clean()
  257. if self.vector and hasattr(self.vector, "clean"):
  258. self.vector.clean()
  259. # Event methods
  260. def on_add(self, schema, fieldname):
  261. pass
  262. def on_remove(self, schema, fieldname):
  263. pass
  264. class ID(FieldType):
  265. """Configured field type that indexes the entire value of the field as one
  266. token. This is useful for data you don't want to tokenize, such as the path
  267. of a file.
  268. """
  269. __inittypes__ = dict(stored=bool, unique=bool, field_boost=float)
  270. def __init__(self, stored=False, unique=False, field_boost=1.0,
  271. spelling=False, sortable=False, analyzer=None):
  272. """
  273. :param stored: Whether the value of this field is stored with the
  274. document.
  275. """
  276. self.analyzer = analyzer or analysis.IDAnalyzer()
  277. self.format = formats.Existence(field_boost=field_boost)
  278. self.stored = stored
  279. self.unique = unique
  280. self.spelling = spelling
  281. self.set_sortable(sortable)
  282. class IDLIST(FieldType):
  283. """Configured field type for fields containing IDs separated by whitespace
  284. and/or punctuation (or anything else, using the expression param).
  285. """
  286. __inittypes__ = dict(stored=bool, unique=bool, expression=bool,
  287. field_boost=float)
  288. def __init__(self, stored=False, unique=False, expression=None,
  289. field_boost=1.0, spelling=False):
  290. """
  291. :param stored: Whether the value of this field is stored with the
  292. document.
  293. :param unique: Whether the value of this field is unique per-document.
  294. :param expression: The regular expression object to use to extract
  295. tokens. The default expression breaks tokens on CRs, LFs, tabs,
  296. spaces, commas, and semicolons.
  297. """
  298. expression = expression or re.compile(r"[^\r\n\t ,;]+")
  299. self.analyzer = analysis.RegexAnalyzer(expression=expression)
  300. self.format = formats.Existence(field_boost=field_boost)
  301. self.stored = stored
  302. self.unique = unique
  303. self.spelling = spelling
  304. class NUMERIC(FieldType):
  305. """Special field type that lets you index integer or floating point
  306. numbers in relatively short fixed-width terms. The field converts numbers
  307. to sortable bytes for you before indexing.
  308. You specify the numeric type of the field (``int`` or ``float``) when you
  309. create the ``NUMERIC`` object. The default is ``int``. For ``int``, you can
  310. specify a size in bits (``32`` or ``64``). For both ``int`` and ``float``
  311. you can specify a ``signed`` keyword argument (default is ``True``).
  312. >>> schema = Schema(path=STORED, position=NUMERIC(int, 64, signed=False))
  313. >>> ix = storage.create_index(schema)
  314. >>> with ix.writer() as w:
  315. ... w.add_document(path="/a", position=5820402204)
  316. ...
  317. You can also use the NUMERIC field to store Decimal instances by specifying
  318. a type of ``int`` or ``long`` and the ``decimal_places`` keyword argument.
  319. This simply multiplies each number by ``(10 ** decimal_places)`` before
  320. storing it as an integer. Of course this may throw away decimal prcesision
  321. (by truncating, not rounding) and imposes the same maximum value limits as
  322. ``int``/``long``, but these may be acceptable for certain applications.
  323. >>> from decimal import Decimal
  324. >>> schema = Schema(path=STORED, position=NUMERIC(int, decimal_places=4))
  325. >>> ix = storage.create_index(schema)
  326. >>> with ix.writer() as w:
  327. ... w.add_document(path="/a", position=Decimal("123.45")
  328. ...
  329. """
  330. def __init__(self, numtype=int, bits=32, stored=False, unique=False,
  331. field_boost=1.0, decimal_places=0, shift_step=4, signed=True,
  332. sortable=False, default=None):
  333. """
  334. :param numtype: the type of numbers that can be stored in this field,
  335. either ``int``, ``float``. If you use ``Decimal``,
  336. use the ``decimal_places`` argument to control how many decimal
  337. places the field will store.
  338. :param stored: Whether the value of this field is stored with the
  339. document.
  340. :param unique: Whether the value of this field is unique per-document.
  341. :param decimal_places: specifies the number of decimal places to save
  342. when storing Decimal instances. If you set this, you will always
  343. get Decimal instances back from the field.
  344. :param shift_steps: The number of bits of precision to shift away at
  345. each tiered indexing level. Values should generally be 1-8. Lower
  346. values yield faster searches but take up more space. A value
  347. of `0` means no tiered indexing.
  348. :param signed: Whether the numbers stored in this field may be
  349. negative.
  350. """
  351. # Allow users to specify strings instead of Python types in case
  352. # docstring isn't clear
  353. if numtype == "int":
  354. numtype = int
  355. if numtype == "float":
  356. numtype = float
  357. # Raise an error if the user tries to use a type other than int or
  358. # float
  359. if numtype is Decimal:
  360. raise TypeError("To store Decimal instances, set type to int use "
  361. "the decimal_places argument")
  362. elif numtype not in (int, float):
  363. raise TypeError("Can't use %r as a type, use int or float"
  364. % numtype)
  365. # Sanity check
  366. if numtype is float and decimal_places:
  367. raise Exception("A float type and decimal_places argument %r are "
  368. "incompatible" % decimal_places)
  369. # Set up field configuration based on type and size
  370. if numtype is float:
  371. bits = 64 # Floats are converted to 64 bit ints
  372. intsizes = [8, 16, 32, 64]
  373. intcodes = ["B", "H", "I", "Q"]
  374. if bits not in intsizes:
  375. raise Exception("Invalid bits %r, use 8, 16, 32, or 64"
  376. % bits)
  377. # Type code for the *sortable* representation
  378. self.sortable_typecode = intcodes[intsizes.index(bits)]
  379. self._struct = struct.Struct(">" + self.sortable_typecode)
  380. self.numtype = numtype
  381. self.bits = bits
  382. self.stored = stored
  383. self.unique = unique
  384. self.decimal_places = decimal_places
  385. self.shift_step = shift_step
  386. self.signed = signed
  387. self.analyzer = analysis.IDAnalyzer()
  388. self.format = formats.Existence(field_boost=field_boost)
  389. # Column configuration
  390. if default is None:
  391. if numtype is int:
  392. default = typecode_max[self.sortable_typecode]
  393. else:
  394. default = NaN
  395. elif not self.is_valid(default):
  396. raise Exception("The default %r is not a valid number for this "
  397. "field" % default)
  398. self.default = default
  399. self.set_sortable(sortable)
  400. def __getstate__(self):
  401. d = self.__dict__.copy()
  402. del d["_struct"]
  403. return d
  404. def __setstate__(self, d):
  405. self.__dict__.update(d)
  406. self._struct = struct.Struct(">" + self.sortable_typecode)
  407. def default_column(self):
  408. return columns.NumericColumn(self.sortable_typecode,
  409. default=self.default)
  410. def is_valid(self, x):
  411. try:
  412. x = self.to_bytes(x)
  413. except ValueError:
  414. return False
  415. except OverflowError:
  416. return False
  417. return True
  418. def index(self, num, **kwargs):
  419. # If the user gave us a list of numbers, recurse on the list
  420. if isinstance(num, (list, tuple)):
  421. for n in num:
  422. for item in self.index(n):
  423. yield item
  424. return
  425. # word, freq, weight, valuestring
  426. if self.shift_step:
  427. for shift in xrange(0, self.bits, self.shift_step):
  428. yield (self.to_bytes(num, shift), 1, 1.0, emptybytes)
  429. else:
  430. yield (self.to_bytes(num), 1, 1.0, emptybytes)
  431. def prepare_number(self, x):
  432. if x == emptybytes or x is None:
  433. return x
  434. dc = self.decimal_places
  435. if dc and isinstance(x, (string_type, Decimal)):
  436. x = Decimal(x) * (10 ** dc)
  437. x = self.numtype(x)
  438. return x
  439. def unprepare_number(self, x):
  440. dc = self.decimal_places
  441. if dc:
  442. s = str(x)
  443. x = Decimal(s[:-dc] + "." + s[-dc:])
  444. return x
  445. def to_column_value(self, x):
  446. if isinstance(x, (list, tuple, array)):
  447. x = x[0]
  448. x = self.prepare_number(x)
  449. return to_sortable(self.numtype, self.bits, self.signed, x)
  450. def from_column_value(self, x):
  451. x = from_sortable(self.numtype, self.bits, self.signed, x)
  452. return self.unprepare_number(x)
  453. def to_bytes(self, x, shift=0):
  454. # Try to avoid re-encoding; this sucks because on Python 2 we can't
  455. # tell the difference between a string and encoded bytes, so we have
  456. # to require the user use unicode when they mean string
  457. if isinstance(x, bytes_type):
  458. return x
  459. if x == emptybytes or x is None:
  460. return self.sortable_to_bytes(0)
  461. x = self.prepare_number(x)
  462. x = to_sortable(self.numtype, self.bits, self.signed, x)
  463. return self.sortable_to_bytes(x, shift)
  464. def sortable_to_bytes(self, x, shift=0):
  465. if shift:
  466. x >>= shift
  467. return pack_byte(shift) + self._struct.pack(x)
  468. def from_bytes(self, bs):
  469. x = self._struct.unpack(bs[1:])[0]
  470. x = from_sortable(self.numtype, self.bits, self.signed, x)
  471. x = self.unprepare_number(x)
  472. return x
  473. def process_text(self, text, **kwargs):
  474. return (self.to_bytes(text),)
  475. def self_parsing(self):
  476. return True
  477. def parse_query(self, fieldname, qstring, boost=1.0):
  478. from whoosh import query
  479. from whoosh.qparser.common import QueryParserError
  480. if qstring == "*":
  481. return query.Every(fieldname, boost=boost)
  482. if not self.is_valid(qstring):
  483. raise QueryParserError("%r is not a valid number" % qstring)
  484. token = self.to_bytes(qstring)
  485. return query.Term(fieldname, token, boost=boost)
  486. def parse_range(self, fieldname, start, end, startexcl, endexcl,
  487. boost=1.0):
  488. from whoosh import query
  489. from whoosh.qparser.common import QueryParserError
  490. if start is not None:
  491. if not self.is_valid(start):
  492. raise QueryParserError("Range start %r is not a valid number"
  493. % start)
  494. start = self.prepare_number(start)
  495. if end is not None:
  496. if not self.is_valid(end):
  497. raise QueryParserError("Range end %r is not a valid number"
  498. % end)
  499. end = self.prepare_number(end)
  500. return query.NumericRange(fieldname, start, end, startexcl, endexcl,
  501. boost=boost)
  502. def sortable_terms(self, ixreader, fieldname):
  503. zero = b("\x00")
  504. for token in ixreader.lexicon(fieldname):
  505. if token[0:1] != zero:
  506. # Only yield the full-precision values
  507. break
  508. yield token
  509. class DATETIME(NUMERIC):
  510. """Special field type that lets you index datetime objects. The field
  511. converts the datetime objects to sortable text for you before indexing.
  512. Since this field is based on Python's datetime module it shares all the
  513. limitations of that module, such as the inability to represent dates before
  514. year 1 in the proleptic Gregorian calendar. However, since this field
  515. stores datetimes as an integer number of microseconds, it could easily
  516. represent a much wider range of dates if the Python datetime implementation
  517. ever supports them.
  518. >>> schema = Schema(path=STORED, date=DATETIME)
  519. >>> ix = storage.create_index(schema)
  520. >>> w = ix.writer()
  521. >>> w.add_document(path="/a", date=datetime.now())
  522. >>> w.commit()
  523. """
  524. __inittypes__ = dict(stored=bool, unique=bool)
  525. def __init__(self, stored=False, unique=False, sortable=False):
  526. """
  527. :param stored: Whether the value of this field is stored with the
  528. document.
  529. :param unique: Whether the value of this field is unique per-document.
  530. """
  531. super(DATETIME, self).__init__(int, 64, stored=stored,
  532. unique=unique, shift_step=8,
  533. sortable=sortable)
  534. def prepare_datetime(self, x):
  535. from whoosh.util.times import floor
  536. if isinstance(x, text_type):
  537. # For indexing, support same strings as for query parsing --
  538. # convert unicode to datetime object
  539. x = self._parse_datestring(x)
  540. x = floor(x) # this makes most sense (unspecified = lowest)
  541. if isinstance(x, datetime.datetime):
  542. return datetime_to_long(x)
  543. elif isinstance(x, bytes_type):
  544. return x
  545. else:
  546. raise Exception("%r is not a datetime" % (x,))
  547. def to_column_value(self, x):
  548. if isinstance(x, bytes_type):
  549. raise Exception("%r is not a datetime" % (x,))
  550. if isinstance(x, (list, tuple)):
  551. x = x[0]
  552. return self.prepare_datetime(x)
  553. def from_column_value(self, x):
  554. return long_to_datetime(x)
  555. def to_bytes(self, x, shift=0):
  556. x = self.prepare_datetime(x)
  557. return NUMERIC.to_bytes(self, x, shift=shift)
  558. def from_bytes(self, bs):
  559. x = NUMERIC.from_bytes(self, bs)
  560. return long_to_datetime(x)
  561. def _parse_datestring(self, qstring):
  562. # This method parses a very simple datetime representation of the form
  563. # YYYY[MM[DD[hh[mm[ss[uuuuuu]]]]]]
  564. from whoosh.util.times import adatetime, fix, is_void
  565. qstring = qstring.replace(" ", "").replace("-", "").replace(".", "")
  566. year = month = day = hour = minute = second = microsecond = None
  567. if len(qstring) >= 4:
  568. year = int(qstring[:4])
  569. if len(qstring) >= 6:
  570. month = int(qstring[4:6])
  571. if len(qstring) >= 8:
  572. day = int(qstring[6:8])
  573. if len(qstring) >= 10:
  574. hour = int(qstring[8:10])
  575. if len(qstring) >= 12:
  576. minute = int(qstring[10:12])
  577. if len(qstring) >= 14:
  578. second = int(qstring[12:14])
  579. if len(qstring) == 20:
  580. microsecond = int(qstring[14:])
  581. at = fix(adatetime(year, month, day, hour, minute, second,
  582. microsecond))
  583. if is_void(at):
  584. raise Exception("%r is not a parseable date" % qstring)
  585. return at
  586. def parse_query(self, fieldname, qstring, boost=1.0):
  587. from whoosh import query
  588. from whoosh.util.times import is_ambiguous
  589. try:
  590. at = self._parse_datestring(qstring)
  591. except:
  592. e = sys.exc_info()[1]
  593. return query.error_query(e)
  594. if is_ambiguous(at):
  595. startnum = datetime_to_long(at.floor())
  596. endnum = datetime_to_long(at.ceil())
  597. return query.NumericRange(fieldname, startnum, endnum)
  598. else:
  599. return query.Term(fieldname, at, boost=boost)
  600. def parse_range(self, fieldname, start, end, startexcl, endexcl,
  601. boost=1.0):
  602. from whoosh import query
  603. if start is None and end is None:
  604. return query.Every(fieldname, boost=boost)
  605. if start is not None:
  606. startdt = self._parse_datestring(start).floor()
  607. start = datetime_to_long(startdt)
  608. if end is not None:
  609. enddt = self._parse_datestring(end).ceil()
  610. end = datetime_to_long(enddt)
  611. return query.NumericRange(fieldname, start, end, boost=boost)
  612. class BOOLEAN(FieldType):
  613. """Special field type that lets you index boolean values (True and False).
  614. The field converts the boolean values to text for you before indexing.
  615. >>> schema = Schema(path=STORED, done=BOOLEAN)
  616. >>> ix = storage.create_index(schema)
  617. >>> w = ix.writer()
  618. >>> w.add_document(path="/a", done=False)
  619. >>> w.commit()
  620. """
  621. bytestrings = (b("f"), b("t"))
  622. trues = frozenset(u("t true yes 1").split())
  623. falses = frozenset(u("f false no 0").split())
  624. __inittypes__ = dict(stored=bool, field_boost=float)
  625. def __init__(self, stored=False, field_boost=1.0):
  626. """
  627. :param stored: Whether the value of this field is stored with the
  628. document.
  629. """
  630. self.stored = stored
  631. self.field_boost = field_boost
  632. self.format = formats.Existence(field_boost=field_boost)
  633. def _obj_to_bool(self, x):
  634. if isinstance(x, string_type):
  635. x = x.lower() in self.trues
  636. else:
  637. x = bool(x)
  638. return x
  639. def to_bytes(self, x):
  640. if isinstance(x, bytes_type):
  641. return x
  642. elif isinstance(x, string_type):
  643. x = x.lower() in self.trues
  644. else:
  645. x = bool(x)
  646. bs = self.bytestrings[int(x)]
  647. return bs
  648. def index(self, bit, **kwargs):
  649. if isinstance(bit, string_type):
  650. bit = bit.lower() in self.trues
  651. else:
  652. bit = bool(bit)
  653. # word, freq, weight, valuestring
  654. return [(self.bytestrings[int(bit)], 1, 1.0, emptybytes)]
  655. def self_parsing(self):
  656. return True
  657. def parse_query(self, fieldname, qstring, boost=1.0):
  658. from whoosh import query
  659. if qstring == "*":
  660. return query.Every(fieldname, boost=boost)
  661. return query.Term(fieldname, self._obj_to_bool(qstring), boost=boost)
  662. class STORED(FieldType):
  663. """Configured field type for fields you want to store but not index.
  664. """
  665. indexed = False
  666. stored = True
  667. def __init__(self):
  668. pass
  669. class COLUMN(FieldType):
  670. """Configured field type for fields you want to store as a per-document
  671. value column but not index.
  672. """
  673. indexed = False
  674. stored = False
  675. def __init__(self, columnobj=None):
  676. if columnobj is None:
  677. columnobj = columns.VarBytesColumn()
  678. if not isinstance(columnobj, columns.Column):
  679. raise TypeError("%r is not a column object" % (columnobj,))
  680. self.column_type = columnobj
  681. def to_bytes(self, v):
  682. return v
  683. def from_bytes(self, b):
  684. return b
  685. class KEYWORD(FieldType):
  686. """Configured field type for fields containing space-separated or
  687. comma-separated keyword-like data (such as tags). The default is to not
  688. store positional information (so phrase searching is not allowed in this
  689. field) and to not make the field scorable.
  690. """
  691. __inittypes__ = dict(stored=bool, lowercase=bool, commas=bool,
  692. scorable=bool, unique=bool, field_boost=float)
  693. def __init__(self, stored=False, lowercase=False, commas=False,
  694. vector=None, scorable=False, unique=False, field_boost=1.0,
  695. spelling=False, sortable=False):
  696. """
  697. :param stored: Whether to store the value of the field with the
  698. document.
  699. :param comma: Whether this is a comma-separated field. If this is False
  700. (the default), it is treated as a space-separated field.
  701. :param scorable: Whether this field is scorable.
  702. """
  703. self.analyzer = analysis.KeywordAnalyzer(lowercase=lowercase,
  704. commas=commas)
  705. self.format = formats.Frequency(field_boost=field_boost)
  706. self.scorable = scorable
  707. self.stored = stored
  708. self.unique = unique
  709. self.spelling = spelling
  710. if vector:
  711. if type(vector) is type:
  712. vector = vector()
  713. elif isinstance(vector, formats.Format):
  714. pass
  715. else:
  716. vector = self.format
  717. else:
  718. vector = None
  719. self.vector = vector
  720. if sortable:
  721. self.column_type = self.default_column()
  722. class TEXT(FieldType):
  723. """Configured field type for text fields (for example, the body text of an
  724. article). The default is to store positional information to allow phrase
  725. searching. This field type is always scorable.
  726. """
  727. __inittypes__ = dict(analyzer=analysis.Analyzer, phrase=bool,
  728. vector=object, stored=bool, field_boost=float)
  729. def __init__(self, analyzer=None, phrase=True, chars=False, vector=None,
  730. stored=False, field_boost=1.0, multitoken_query="default",
  731. spelling=False, sortable=False, lang=None):
  732. """
  733. :param analyzer: The analysis.Analyzer to use to index the field
  734. contents. See the analysis module for more information. If you omit
  735. this argument, the field uses analysis.StandardAnalyzer.
  736. :param phrase: Whether the store positional information to allow phrase
  737. searching.
  738. :param chars: Whether to store character ranges along with positions.
  739. If this is True, "phrase" is also implied.
  740. :param vector: A :class:`whoosh.formats.Format` object to use to store
  741. term vectors, or ``True`` to store vectors using the same format as
  742. the inverted index, or ``None`` or ``False`` to not store vectors.
  743. By default, fields do not store term vectors.
  744. :param stored: Whether to store the value of this field with the
  745. document. Since this field type generally contains a lot of text,
  746. you should avoid storing it with the document unless you need to,
  747. for example to allow fast excerpts in the search results.
  748. :param spelling: Whether to generate word graphs for this field to make
  749. spelling suggestions much faster.
  750. :param sortable: If True, make this field sortable using the default
  751. column type. If you pass a :class:`whoosh.columns.Column` instance
  752. instead of True, the field will use the given column type.
  753. :param lang: automaticaly configure a
  754. :class:`whoosh.analysis.LanguageAnalyzer` for the given language.
  755. This is ignored if you also specify an ``analyzer``.
  756. """
  757. if analyzer:
  758. self.analyzer = analyzer
  759. elif lang:
  760. self.analyzer = analysis.LanguageAnalyzer(lang)
  761. else:
  762. self.analyzer = analysis.StandardAnalyzer()
  763. if chars:
  764. formatclass = formats.Characters
  765. elif phrase:
  766. formatclass = formats.Positions
  767. else:
  768. formatclass = formats.Frequency
  769. self.format = formatclass(field_boost=field_boost)
  770. if vector:
  771. if type(vector) is type:
  772. vector = vector()
  773. elif isinstance(vector, formats.Format):
  774. pass
  775. else:
  776. vector = formatclass()
  777. else:
  778. vector = None
  779. self.vector = vector
  780. if sortable:
  781. if isinstance(sortable, columns.Column):
  782. self.column_type = sortable
  783. else:
  784. self.column_type = columns.VarBytesColumn()
  785. else:
  786. self.column_type = None
  787. self.multitoken_query = multitoken_query
  788. self.scorable = True
  789. self.stored = stored
  790. self.spelling = spelling
  791. class NGRAM(FieldType):
  792. """Configured field that indexes text as N-grams. For example, with a field
  793. type NGRAM(3,4), the value "hello" will be indexed as tokens
  794. "hel", "hell", "ell", "ello", "llo". This field type chops the entire text
  795. into N-grams, including whitespace and punctuation. See :class:`NGRAMWORDS`
  796. for a field type that breaks the text into words first before chopping the
  797. words into N-grams.
  798. """
  799. __inittypes__ = dict(minsize=int, maxsize=int, stored=bool,
  800. field_boost=float, queryor=bool, phrase=bool)
  801. scorable = True
  802. def __init__(self, minsize=2, maxsize=4, stored=False, field_boost=1.0,
  803. queryor=False, phrase=False, sortable=False):
  804. """
  805. :param minsize: The minimum length of the N-grams.
  806. :param maxsize: The maximum length of the N-grams.
  807. :param stored: Whether to store the value of this field with the
  808. document. Since this field type generally contains a lot of text,
  809. you should avoid storing it with the document unless you need to,
  810. for example to allow fast excerpts in the search results.
  811. :param queryor: if True, combine the N-grams with an Or query. The
  812. default is to combine N-grams with an And query.
  813. :param phrase: store positions on the N-grams to allow exact phrase
  814. searching. The default is off.
  815. """
  816. formatclass = formats.Frequency
  817. if phrase:
  818. formatclass = formats.Positions
  819. self.analyzer = analysis.NgramAnalyzer(minsize, maxsize)
  820. self.format = formatclass(field_boost=field_boost)
  821. self.stored = stored
  822. self.queryor = queryor
  823. self.set_sortable(sortable)
  824. def self_parsing(self):
  825. return True
  826. def parse_query(self, fieldname, qstring, boost=1.0):
  827. from whoosh import query
  828. terms = [query.Term(fieldname, g)
  829. for g in self.process_text(qstring, mode='query')]
  830. cls = query.Or if self.queryor else query.And
  831. return cls(terms, boost=boost)
  832. class NGRAMWORDS(NGRAM):
  833. """Configured field that chops text into words using a tokenizer,
  834. lowercases the words, and then chops the words into N-grams.
  835. """
  836. __inittypes__ = dict(minsize=int, maxsize=int, stored=bool,
  837. field_boost=float, tokenizer=analysis.Tokenizer,
  838. at=str, queryor=bool)
  839. scorable = True
  840. def __init__(self, minsize=2, maxsize=4, stored=False, field_boost=1.0,
  841. tokenizer=None, at=None, queryor=False, sortable=False):
  842. """
  843. :param minsize: The minimum length of the N-grams.
  844. :param maxsize: The maximum length of the N-grams.
  845. :param stored: Whether to store the value of this field with the
  846. document. Since this field type generally contains a lot of text,
  847. you should avoid storing it with the document unless you need to,
  848. for example to allow fast excerpts in the search results.
  849. :param tokenizer: an instance of :class:`whoosh.analysis.Tokenizer`
  850. used to break the text into words.
  851. :param at: if 'start', only takes N-grams from the start of the word.
  852. If 'end', only takes N-grams from the end. Otherwise the default
  853. is to take all N-grams from each word.
  854. :param queryor: if True, combine the N-grams with an Or query. The
  855. default is to combine N-grams with an And query.
  856. """
  857. self.analyzer = analysis.NgramWordAnalyzer(minsize, maxsize, tokenizer,
  858. at=at)
  859. self.format = formats.Frequency(field_boost=field_boost)
  860. self.stored = stored
  861. self.queryor = queryor
  862. self.set_sortable(sortable)
  863. # Schema class
  864. class MetaSchema(type):
  865. def __new__(cls, name, bases, attrs):
  866. super_new = super(MetaSchema, cls).__new__
  867. if not any(b for b in bases if isinstance(b, MetaSchema)):
  868. # If this isn't a subclass of MetaSchema, don't do anything special
  869. return super_new(cls, name, bases, attrs)
  870. # Create the class
  871. special_attrs = {}
  872. for key in list(attrs.keys()):
  873. if key.startswith("__"):
  874. special_attrs[key] = attrs.pop(key)
  875. new_class = super_new(cls, name, bases, special_attrs)
  876. fields = {}
  877. for b in bases:
  878. if hasattr(b, "_clsfields"):
  879. fields.update(b._clsfields)
  880. fields.update(attrs)
  881. new_class._clsfields = fields
  882. return new_class
  883. def schema(self):
  884. return Schema(**self._clsfields)
  885. class Schema(object):
  886. """Represents the collection of fields in an index. Maps field names to
  887. FieldType objects which define the behavior of each field.
  888. Low-level parts of the index use field numbers instead of field names for
  889. compactness. This class has several methods for converting between the
  890. field name, field number, and field object itself.
  891. """
  892. def __init__(self, **fields):
  893. """ All keyword arguments to the constructor are treated as fieldname =
  894. fieldtype pairs. The fieldtype can be an instantiated FieldType object,
  895. or a FieldType sub-class (in which case the Schema will instantiate it
  896. with the default constructor before adding it).
  897. For example::
  898. s = Schema(content = TEXT,
  899. title = TEXT(stored = True),
  900. tags = KEYWORD(stored = True))
  901. """
  902. self._fields = {}
  903. self._dyn_fields = {}
  904. for name in sorted(fields.keys()):
  905. self.add(name, fields[name])
  906. def copy(self):
  907. """Returns a shallow copy of the schema. The field instances are not
  908. deep copied, so they are shared between schema copies.
  909. """
  910. return self.__class__(**self._fields)
  911. def __eq__(self, other):
  912. return (other.__class__ is self.__class__
  913. and list(self.items()) == list(other.items()))
  914. def __ne__(self, other):
  915. return not(self.__eq__(other))
  916. def __repr__(self):
  917. return "<%s: %r>" % (self.__class__.__name__, self.names())
  918. def __iter__(self):
  919. """Returns the field objects in this schema.
  920. """
  921. return iter(itervalues(self._fields))
  922. def __getitem__(self, name):
  923. """Returns the field associated with the given field name.
  924. """
  925. if name in self._fields:
  926. return self._fields[name]
  927. for expr, fieldtype in itervalues(self._dyn_fields):
  928. if expr.match(name):
  929. return fieldtype
  930. raise KeyError("No field named %r" % (name,))
  931. def __len__(self):
  932. """Returns the number of fields in this schema.
  933. """
  934. return len(self._fields)
  935. def __contains__(self, fieldname):
  936. """Returns True if a field by the given name is in this schema.
  937. """
  938. # Defined in terms of __getitem__ so that there's only one method to
  939. # override to provide dynamic fields
  940. try:
  941. field = self[fieldname]
  942. return field is not None
  943. except KeyError:
  944. return False
  945. def items(self):
  946. """Returns a list of ("fieldname", field_object) pairs for the fields
  947. in this schema.
  948. """
  949. return sorted(self._fields.items())
  950. def names(self, check_names=None):
  951. """Returns a list of the names of the fields in this schema.
  952. :param check_names: (optional) sequence of field names to check
  953. whether the schema accepts them as (dynamic) field names -
  954. acceptable names will also be in the result list.
  955. Note: You may also have static field names in check_names, that
  956. won't create duplicates in the result list. Unsupported names
  957. will not be in the result list.
  958. """
  959. fieldnames = set(self._fields.keys())
  960. if check_names is not None:
  961. check_names = set(check_names) - fieldnames
  962. fieldnames.update(fieldname for fieldname in check_names
  963. if fieldname in self)
  964. return sorted(fieldnames)
  965. def clean(self):
  966. for field in self:
  967. field.clean()
  968. def add(self, name, fieldtype, glob=False):
  969. """Adds a field to this schema.
  970. :param name: The name of the field.
  971. :param fieldtype: An instantiated fields.FieldType object, or a
  972. FieldType subclass. If you pass an instantiated object, the schema
  973. will use that as the field configuration for this field. If you
  974. pass a FieldType subclass, the schema will automatically
  975. instantiate it with the default constructor.
  976. """
  977. # Check field name
  978. if name.startswith("_"):
  979. raise FieldConfigurationError("Field names cannot start with an "
  980. "underscore")
  981. if " " in name:
  982. raise FieldConfigurationError("Field names cannot contain spaces")
  983. if name in self._fields or (glob and name in self._dyn_fields):
  984. raise FieldConfigurationError("Schema already has a field %r"
  985. % name)
  986. # If the user passed a type rather than an instantiated field object,
  987. # instantiate it automatically
  988. if type(fieldtype) is type:
  989. try:
  990. fieldtype = fieldtype()
  991. except:
  992. e = sys.exc_info()[1]
  993. raise FieldConfigurationError("Error: %s instantiating field "
  994. "%r: %r" % (e, name, fieldtype))
  995. if not isinstance(fieldtype, FieldType):
  996. raise FieldConfigurationError("%r is not a FieldType object"
  997. % fieldtype)
  998. if glob:
  999. expr = re.compile(fnmatch.translate(name))
  1000. self._dyn_fields[name] = (expr, fieldtype)
  1001. else:
  1002. fieldtype.on_add(self, name)
  1003. self._fields[name] = fieldtype
  1004. def remove(self, fieldname):
  1005. if fieldname in self._fields:
  1006. self._fields[fieldname].on_remove(self, fieldname)
  1007. del self._fields[fieldname]
  1008. elif fieldname in self._dyn_fields:
  1009. del self._dyn_fields[fieldname]
  1010. else:
  1011. raise KeyError("No field named %r" % fieldname)
  1012. def has_vectored_fields(self):
  1013. """Returns True if any of the fields in this schema store term vectors.
  1014. """
  1015. return any(ftype.vector for ftype in self)
  1016. def has_scorable_fields(self):
  1017. return any(ftype.scorable for ftype in self)
  1018. def stored_names(self):
  1019. """Returns a list of the names of fields that are stored.
  1020. """
  1021. return [name for name, field in self.items() if field.stored]
  1022. def scorable_names(self):
  1023. """Returns a list of the names of fields that store field
  1024. lengths.
  1025. """
  1026. return [name for name, field in self.items() if field.scorable]
  1027. def vector_names(self):
  1028. """Returns a list of the names of fields that store vectors.
  1029. """
  1030. return [name for name, field in self.items() if field.vector]
  1031. def separate_spelling_names(self):
  1032. """Returns a list of the names of fields that require special handling
  1033. for generating spelling graphs... either because they store graphs but
  1034. aren't indexed, or because the analyzer is stemmed.
  1035. """
  1036. return [name for name, field in self.items()
  1037. if field.spelling and field.separate_spelling()]
  1038. class SchemaClass(with_metaclass(MetaSchema, Schema)):
  1039. """Allows you to define a schema using declarative syntax, similar to
  1040. Django models::
  1041. class MySchema(SchemaClass):
  1042. path = ID
  1043. date = DATETIME
  1044. content = TEXT
  1045. You can use inheritance to share common fields between schemas::
  1046. class Parent(SchemaClass):
  1047. path = ID(stored=True)
  1048. date = DATETIME
  1049. class Child1(Parent):
  1050. content = TEXT(positions=False)
  1051. class Child2(Parent):
  1052. tags = KEYWORD
  1053. This class overrides ``__new__`` so instantiating your sub-class always
  1054. results in an instance of ``Schema``.
  1055. >>> class MySchema(SchemaClass):
  1056. ... title = TEXT(stored=True)
  1057. ... content = TEXT
  1058. ...
  1059. >>> s = MySchema()
  1060. >>> type(s)
  1061. <class 'whoosh.fields.Schema'>
  1062. """
  1063. def __new__(cls, *args, **kwargs):
  1064. obj = super(Schema, cls).__new__(Schema)
  1065. kw = getattr(cls, "_clsfields", {})
  1066. kw.update(kwargs)
  1067. obj.__init__(*args, **kw)
  1068. return obj
  1069. def ensure_schema(schema):
  1070. if isinstance(schema, type) and issubclass(schema, Schema):
  1071. schema = schema.schema()
  1072. if not isinstance(schema, Schema):
  1073. raise FieldConfigurationError("%r is not a Schema" % schema)
  1074. return schema
  1075. def merge_fielddict(d1, d2):
  1076. keyset = set(d1.keys()) | set(d2.keys())
  1077. out = {}
  1078. for name in keyset:
  1079. field1 = d1.get(name)
  1080. field2 = d2.get(name)
  1081. if field1 and field2 and field1 != field2:
  1082. raise Exception("Inconsistent field %r: %r != %r"
  1083. % (name, field1, field2))
  1084. out[name] = field1 or field2
  1085. return out
  1086. def merge_schema(s1, s2):
  1087. schema = Schema()
  1088. schema._fields = merge_fielddict(s1._fields, s2._fields)
  1089. schema._dyn_fields = merge_fielddict(s1._dyn_fields, s2._dyn_fields)
  1090. return schema
  1091. def merge_schemas(schemas):
  1092. schema = schemas[0]
  1093. for i in xrange(1, len(schemas)):
  1094. schema = merge_schema(schema, schemas[i])
  1095. return schema