fields.py 55 KB

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