writing.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. # Copyright 2007 Matt Chaput. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are met:
  5. #
  6. # 1. Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. #
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
  14. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. #
  24. # The views and conclusions contained in the software and documentation are
  25. # those of the authors and should not be interpreted as representing official
  26. # policies, either expressed or implied, of Matt Chaput.
  27. from __future__ import with_statement
  28. import threading, time
  29. from bisect import bisect_right
  30. from contextlib import contextmanager
  31. from whoosh import columns
  32. from whoosh.compat import abstractmethod, bytes_type
  33. from whoosh.externalsort import SortingPool
  34. from whoosh.fields import UnknownFieldError
  35. from whoosh.index import LockError
  36. from whoosh.system import emptybytes
  37. from whoosh.util import fib, random_name
  38. from whoosh.util.filelock import try_for
  39. from whoosh.util.text import utf8encode
  40. # Exceptions
  41. class IndexingError(Exception):
  42. pass
  43. # Document grouping context manager
  44. @contextmanager
  45. def groupmanager(writer):
  46. writer.start_group()
  47. yield
  48. writer.end_group()
  49. # Merge policies
  50. # A merge policy is a callable that takes the Index object, the SegmentWriter
  51. # object, and the current segment list (not including the segment being
  52. # written), and returns an updated segment list (not including the segment
  53. # being written).
  54. def NO_MERGE(writer, segments):
  55. """This policy does not merge any existing segments.
  56. """
  57. return segments
  58. def MERGE_SMALL(writer, segments):
  59. """This policy merges small segments, where "small" is defined using a
  60. heuristic based on the fibonacci sequence.
  61. """
  62. from whoosh.reading import SegmentReader
  63. unchanged_segments = []
  64. segments_to_merge = []
  65. sorted_segment_list = sorted(segments, key=lambda s: s.doc_count_all())
  66. total_docs = 0
  67. merge_point_found = False
  68. for i, seg in enumerate(sorted_segment_list):
  69. count = seg.doc_count_all()
  70. if count > 0:
  71. total_docs += count
  72. if merge_point_found: # append the remaining to unchanged
  73. unchanged_segments.append(seg)
  74. else: # look for a merge point
  75. segments_to_merge.append((seg, i)) # merge every segment up to the merge point
  76. if i > 3 and total_docs < fib(i + 5):
  77. merge_point_found = True
  78. if merge_point_found and len(segments_to_merge) > 1:
  79. for seg, i in segments_to_merge:
  80. reader = SegmentReader(writer.storage, writer.schema, seg)
  81. writer.add_reader(reader)
  82. reader.close()
  83. return unchanged_segments
  84. else:
  85. return segments
  86. def OPTIMIZE(writer, segments):
  87. """This policy merges all existing segments.
  88. """
  89. from whoosh.reading import SegmentReader
  90. for seg in segments:
  91. reader = SegmentReader(writer.storage, writer.schema, seg)
  92. writer.add_reader(reader)
  93. reader.close()
  94. return []
  95. def CLEAR(writer, segments):
  96. """This policy DELETES all existing segments and only writes the new
  97. segment.
  98. """
  99. return []
  100. # Customized sorting pool for postings
  101. class PostingPool(SortingPool):
  102. # Subclass whoosh.externalsort.SortingPool to use knowledge of
  103. # postings to set run size in bytes instead of items
  104. namechars = "abcdefghijklmnopqrstuvwxyz0123456789"
  105. def __init__(self, tempstore, segment, limitmb=128, **kwargs):
  106. SortingPool.__init__(self, **kwargs)
  107. self.tempstore = tempstore
  108. self.segment = segment
  109. self.limit = limitmb * 1024 * 1024
  110. self.currentsize = 0
  111. self.fieldnames = set()
  112. def _new_run(self):
  113. path = "%s.run" % random_name()
  114. f = self.tempstore.create_file(path).raw_file()
  115. return path, f
  116. def _open_run(self, path):
  117. return self.tempstore.open_file(path).raw_file()
  118. def _remove_run(self, path):
  119. return self.tempstore.delete_file(path)
  120. def add(self, item):
  121. # item = (fieldname, tbytes, docnum, weight, vbytes)
  122. assert isinstance(item[1], bytes_type), "tbytes=%r" % item[1]
  123. if item[4] is not None:
  124. assert isinstance(item[4], bytes_type), "vbytes=%r" % item[4]
  125. self.fieldnames.add(item[0])
  126. size = (28 + 4 * 5 # tuple = 28 + 4 * length
  127. + 21 + len(item[0]) # fieldname = str = 21 + length
  128. + 26 + len(item[1]) * 2 # text = unicode = 26 + 2 * length
  129. + 18 # docnum = long = 18
  130. + 16 # weight = float = 16
  131. + 21 + len(item[4] or '')) # valuestring
  132. self.currentsize += size
  133. if self.currentsize > self.limit:
  134. self.save()
  135. self.current.append(item)
  136. def iter_postings(self):
  137. # This is just an alias for items() to be consistent with the
  138. # iter_postings()/add_postings() interface of a lot of other classes
  139. return self.items()
  140. def save(self):
  141. SortingPool.save(self)
  142. self.currentsize = 0
  143. # Writer base class
  144. class IndexWriter(object):
  145. """High-level object for writing to an index.
  146. To get a writer for a particular index, call
  147. :meth:`~whoosh.index.Index.writer` on the Index object.
  148. >>> writer = myindex.writer()
  149. You can use this object as a context manager. If an exception is thrown
  150. from within the context it calls :meth:`~IndexWriter.cancel` to clean up
  151. temporary files, otherwise it calls :meth:`~IndexWriter.commit` when the
  152. context exits.
  153. >>> with myindex.writer() as w:
  154. ... w.add_document(title="First document", content="Hello there.")
  155. ... w.add_document(title="Second document", content="This is easy!")
  156. """
  157. def __enter__(self):
  158. return self
  159. def __exit__(self, exc_type, exc_val, exc_tb):
  160. if exc_type:
  161. self.cancel()
  162. else:
  163. self.commit()
  164. def group(self):
  165. """Returns a context manager that calls
  166. :meth:`~IndexWriter.start_group` and :meth:`~IndexWriter.end_group` for
  167. you, allowing you to use a ``with`` statement to group hierarchical
  168. documents::
  169. with myindex.writer() as w:
  170. with w.group():
  171. w.add_document(kind="class", name="Accumulator")
  172. w.add_document(kind="method", name="add")
  173. w.add_document(kind="method", name="get_result")
  174. w.add_document(kind="method", name="close")
  175. with w.group():
  176. w.add_document(kind="class", name="Calculator")
  177. w.add_document(kind="method", name="add")
  178. w.add_document(kind="method", name="multiply")
  179. w.add_document(kind="method", name="get_result")
  180. w.add_document(kind="method", name="close")
  181. """
  182. return groupmanager(self)
  183. def start_group(self):
  184. """Start indexing a group of hierarchical documents. The backend should
  185. ensure that these documents are all added to the same segment::
  186. with myindex.writer() as w:
  187. w.start_group()
  188. w.add_document(kind="class", name="Accumulator")
  189. w.add_document(kind="method", name="add")
  190. w.add_document(kind="method", name="get_result")
  191. w.add_document(kind="method", name="close")
  192. w.end_group()
  193. w.start_group()
  194. w.add_document(kind="class", name="Calculator")
  195. w.add_document(kind="method", name="add")
  196. w.add_document(kind="method", name="multiply")
  197. w.add_document(kind="method", name="get_result")
  198. w.add_document(kind="method", name="close")
  199. w.end_group()
  200. A more convenient way to group documents is to use the
  201. :meth:`~IndexWriter.group` method and the ``with`` statement.
  202. """
  203. pass
  204. def end_group(self):
  205. """Finish indexing a group of hierarchical documents. See
  206. :meth:`~IndexWriter.start_group`.
  207. """
  208. pass
  209. def add_field(self, fieldname, fieldtype, **kwargs):
  210. """Adds a field to the index's schema.
  211. :param fieldname: the name of the field to add.
  212. :param fieldtype: an instantiated :class:`whoosh.fields.FieldType`
  213. object.
  214. """
  215. self.schema.add(fieldname, fieldtype, **kwargs)
  216. def remove_field(self, fieldname, **kwargs):
  217. """Removes the named field from the index's schema. Depending on the
  218. backend implementation, this may or may not actually remove existing
  219. data for the field from the index. Optimizing the index should always
  220. clear out existing data for a removed field.
  221. """
  222. self.schema.remove(fieldname, **kwargs)
  223. @abstractmethod
  224. def reader(self, **kwargs):
  225. """Returns a reader for the existing index.
  226. """
  227. raise NotImplementedError
  228. def searcher(self, **kwargs):
  229. from whoosh.searching import Searcher
  230. return Searcher(self.reader(), **kwargs)
  231. def delete_by_term(self, fieldname, text, searcher=None):
  232. """Deletes any documents containing "term" in the "fieldname" field.
  233. This is useful when you have an indexed field containing a unique ID
  234. (such as "pathname") for each document.
  235. :returns: the number of documents deleted.
  236. """
  237. from whoosh.query import Term
  238. q = Term(fieldname, text)
  239. return self.delete_by_query(q, searcher=searcher)
  240. def delete_by_query(self, q, searcher=None):
  241. """Deletes any documents matching a query object.
  242. :returns: the number of documents deleted.
  243. """
  244. if searcher:
  245. s = searcher
  246. else:
  247. s = self.searcher()
  248. try:
  249. count = 0
  250. for docnum in s.docs_for_query(q, for_deletion=True):
  251. self.delete_document(docnum)
  252. count += 1
  253. finally:
  254. if not searcher:
  255. s.close()
  256. return count
  257. @abstractmethod
  258. def delete_document(self, docnum, delete=True):
  259. """Deletes a document by number.
  260. """
  261. raise NotImplementedError
  262. @abstractmethod
  263. def add_document(self, **fields):
  264. """The keyword arguments map field names to the values to index/store::
  265. w = myindex.writer()
  266. w.add_document(path=u"/a", title=u"First doc", text=u"Hello")
  267. w.commit()
  268. Depending on the field type, some fields may take objects other than
  269. unicode strings. For example, NUMERIC fields take numbers, and DATETIME
  270. fields take ``datetime.datetime`` objects::
  271. from datetime import datetime, timedelta
  272. from whoosh import index
  273. from whoosh.fields import *
  274. schema = Schema(date=DATETIME, size=NUMERIC(float), content=TEXT)
  275. myindex = index.create_in("indexdir", schema)
  276. w = myindex.writer()
  277. w.add_document(date=datetime.now(), size=5.5, content=u"Hello")
  278. w.commit()
  279. Instead of a single object (i.e., unicode string, number, or datetime),
  280. you can supply a list or tuple of objects. For unicode strings, this
  281. bypasses the field's analyzer. For numbers and dates, this lets you add
  282. multiple values for the given field::
  283. date1 = datetime.now()
  284. date2 = datetime(2005, 12, 25)
  285. date3 = datetime(1999, 1, 1)
  286. w.add_document(date=[date1, date2, date3], size=[9.5, 10],
  287. content=[u"alfa", u"bravo", u"charlie"])
  288. For fields that are both indexed and stored, you can specify an
  289. alternate value to store using a keyword argument in the form
  290. "_stored_<fieldname>". For example, if you have a field named "title"
  291. and you want to index the text "a b c" but store the text "e f g", use
  292. keyword arguments like this::
  293. writer.add_document(title=u"a b c", _stored_title=u"e f g")
  294. You can boost the weight of all terms in a certain field by specifying
  295. a ``_<fieldname>_boost`` keyword argument. For example, if you have a
  296. field named "content", you can double the weight of this document for
  297. searches in the "content" field like this::
  298. writer.add_document(content="a b c", _title_boost=2.0)
  299. You can boost every field at once using the ``_boost`` keyword. For
  300. example, to boost fields "a" and "b" by 2.0, and field "c" by 3.0::
  301. writer.add_document(a="alfa", b="bravo", c="charlie",
  302. _boost=2.0, _c_boost=3.0)
  303. Note that some scoring algroithms, including Whoosh's default BM25F,
  304. do not work with term weights less than 1, so you should generally not
  305. use a boost factor less than 1.
  306. See also :meth:`Writer.update_document`.
  307. """
  308. raise NotImplementedError
  309. @abstractmethod
  310. def add_reader(self, reader):
  311. raise NotImplementedError
  312. def _doc_boost(self, fields, default=1.0):
  313. if "_boost" in fields:
  314. return float(fields["_boost"])
  315. else:
  316. return default
  317. def _field_boost(self, fields, fieldname, default=1.0):
  318. boostkw = "_%s_boost" % fieldname
  319. if boostkw in fields:
  320. return float(fields[boostkw])
  321. else:
  322. return default
  323. def _unique_fields(self, fields):
  324. # Check which of the supplied fields are unique
  325. unique_fields = [name for name, field in self.schema.items()
  326. if name in fields and field.unique]
  327. return unique_fields
  328. def update_document(self, **fields):
  329. """The keyword arguments map field names to the values to index/store.
  330. This method adds a new document to the index, and automatically deletes
  331. any documents with the same values in any fields marked "unique" in the
  332. schema::
  333. schema = fields.Schema(path=fields.ID(unique=True, stored=True),
  334. content=fields.TEXT)
  335. myindex = index.create_in("index", schema)
  336. w = myindex.writer()
  337. w.add_document(path=u"/", content=u"Mary had a lamb")
  338. w.commit()
  339. w = myindex.writer()
  340. w.update_document(path=u"/", content=u"Mary had a little lamb")
  341. w.commit()
  342. assert myindex.doc_count() == 1
  343. It is safe to use ``update_document`` in place of ``add_document``; if
  344. there is no existing document to replace, it simply does an add.
  345. You cannot currently pass a list or tuple of values to a "unique"
  346. field.
  347. Because this method has to search for documents with the same unique
  348. fields and delete them before adding the new document, it is slower
  349. than using ``add_document``.
  350. * Marking more fields "unique" in the schema will make each
  351. ``update_document`` call slightly slower.
  352. * When you are updating multiple documents, it is faster to batch
  353. delete all changed documents and then use ``add_document`` to add
  354. the replacements instead of using ``update_document``.
  355. Note that this method will only replace a *committed* document;
  356. currently it cannot replace documents you've added to the IndexWriter
  357. but haven't yet committed. For example, if you do this:
  358. >>> writer.update_document(unique_id=u"1", content=u"Replace me")
  359. >>> writer.update_document(unique_id=u"1", content=u"Replacement")
  360. ...this will add two documents with the same value of ``unique_id``,
  361. instead of the second document replacing the first.
  362. See :meth:`Writer.add_document` for information on
  363. ``_stored_<fieldname>``, ``_<fieldname>_boost``, and ``_boost`` keyword
  364. arguments.
  365. """
  366. # Delete the set of documents matching the unique terms
  367. unique_fields = self._unique_fields(fields)
  368. if unique_fields:
  369. with self.searcher() as s:
  370. uniqueterms = [(name, fields[name]) for name in unique_fields]
  371. docs = s._find_unique(uniqueterms)
  372. for docnum in docs:
  373. self.delete_document(docnum)
  374. # Add the given fields
  375. self.add_document(**fields)
  376. def commit(self):
  377. """Finishes writing and unlocks the index.
  378. """
  379. pass
  380. def cancel(self):
  381. """Cancels any documents/deletions added by this object
  382. and unlocks the index.
  383. """
  384. pass
  385. # Codec-based writer
  386. class SegmentWriter(IndexWriter):
  387. def __init__(self, ix, poolclass=None, timeout=0.0, delay=0.1, _lk=True,
  388. limitmb=128, docbase=0, codec=None, compound=True, **kwargs):
  389. # Lock the index
  390. self.writelock = None
  391. if _lk:
  392. self.writelock = ix.lock("WRITELOCK")
  393. if not try_for(self.writelock.acquire, timeout=timeout,
  394. delay=delay):
  395. raise LockError
  396. if codec is None:
  397. from whoosh.codec import default_codec
  398. codec = default_codec()
  399. self.codec = codec
  400. # Get info from the index
  401. self.storage = ix.storage
  402. self.indexname = ix.indexname
  403. info = ix._read_toc()
  404. self.generation = info.generation + 1
  405. self.schema = info.schema
  406. self.segments = info.segments
  407. self.docnum = self.docbase = docbase
  408. self._setup_doc_offsets()
  409. # Internals
  410. self._tempstorage = self.storage.temp_storage("%s.tmp" % self.indexname)
  411. newsegment = codec.new_segment(self.storage, self.indexname)
  412. self.newsegment = newsegment
  413. self.compound = compound and newsegment.should_assemble()
  414. self.is_closed = False
  415. self._added = False
  416. self.pool = PostingPool(self._tempstorage, self.newsegment,
  417. limitmb=limitmb)
  418. # Set up writers
  419. self.perdocwriter = codec.per_document_writer(self.storage, newsegment)
  420. self.fieldwriter = codec.field_writer(self.storage, newsegment)
  421. self.merge = True
  422. self.optimize = False
  423. self.mergetype = None
  424. def __repr__(self):
  425. return "<%s %r>" % (self.__class__.__name__, self.newsegment)
  426. def _check_state(self):
  427. if self.is_closed:
  428. raise IndexingError("This writer is closed")
  429. def _setup_doc_offsets(self):
  430. self._doc_offsets = []
  431. base = 0
  432. for s in self.segments:
  433. self._doc_offsets.append(base)
  434. base += s.doc_count_all()
  435. def _document_segment(self, docnum):
  436. #Returns the index.Segment object containing the given document
  437. #number.
  438. offsets = self._doc_offsets
  439. if len(offsets) == 1:
  440. return 0
  441. return bisect_right(offsets, docnum) - 1
  442. def _segment_and_docnum(self, docnum):
  443. #Returns an (index.Segment, segment_docnum) pair for the segment
  444. #containing the given document number.
  445. segmentnum = self._document_segment(docnum)
  446. offset = self._doc_offsets[segmentnum]
  447. segment = self.segments[segmentnum]
  448. return segment, docnum - offset
  449. def _process_posts(self, items, startdoc, docmap):
  450. schema = self.schema
  451. for fieldname, text, docnum, weight, vbytes in items:
  452. if fieldname not in schema:
  453. continue
  454. if docmap is not None:
  455. newdoc = docmap[docnum]
  456. else:
  457. newdoc = startdoc + docnum
  458. yield (fieldname, text, newdoc, weight, vbytes)
  459. def temp_storage(self):
  460. return self._tempstorage
  461. def add_field(self, fieldname, fieldspec, **kwargs):
  462. self._check_state()
  463. if self._added:
  464. raise Exception("Can't modify schema after adding data to writer")
  465. super(SegmentWriter, self).add_field(fieldname, fieldspec, **kwargs)
  466. def remove_field(self, fieldname):
  467. self._check_state()
  468. if self._added:
  469. raise Exception("Can't modify schema after adding data to writer")
  470. super(SegmentWriter, self).remove_field(fieldname)
  471. def has_deletions(self):
  472. """
  473. Returns True if the current index has documents that are marked deleted
  474. but haven't been optimized out of the index yet.
  475. """
  476. return any(s.has_deletions() for s in self.segments)
  477. def delete_document(self, docnum, delete=True):
  478. self._check_state()
  479. if docnum >= sum(seg.doc_count_all() for seg in self.segments):
  480. raise IndexingError("No document ID %r in this index" % docnum)
  481. segment, segdocnum = self._segment_and_docnum(docnum)
  482. segment.delete_document(segdocnum, delete=delete)
  483. def deleted_count(self):
  484. """
  485. :returns: the total number of deleted documents in the index.
  486. """
  487. return sum(s.deleted_count() for s in self.segments)
  488. def is_deleted(self, docnum):
  489. segment, segdocnum = self._segment_and_docnum(docnum)
  490. return segment.is_deleted(segdocnum)
  491. def reader(self, reuse=None):
  492. from whoosh.index import FileIndex
  493. self._check_state()
  494. return FileIndex._reader(self.storage, self.schema, self.segments,
  495. self.generation, reuse=reuse)
  496. def iter_postings(self):
  497. return self.pool.iter_postings()
  498. def add_postings_to_pool(self, reader, startdoc, docmap):
  499. items = self._process_posts(reader.iter_postings(), startdoc, docmap)
  500. add_post = self.pool.add
  501. for item in items:
  502. add_post(item)
  503. def write_postings(self, lengths, items, startdoc, docmap):
  504. items = self._process_posts(items, startdoc, docmap)
  505. self.fieldwriter.add_postings(self.schema, lengths, items)
  506. def write_per_doc(self, fieldnames, reader):
  507. # Very bad hack: reader should be an IndexReader, but may be a
  508. # PerDocumentReader if this is called from multiproc, where the code
  509. # tries to be efficient by merging per-doc and terms separately.
  510. # TODO: fix this!
  511. schema = self.schema
  512. if reader.has_deletions():
  513. docmap = {}
  514. else:
  515. docmap = None
  516. pdw = self.perdocwriter
  517. # Open all column readers
  518. cols = {}
  519. for fieldname in fieldnames:
  520. fieldobj = schema[fieldname]
  521. coltype = fieldobj.column_type
  522. if coltype and reader.has_column(fieldname):
  523. creader = reader.column_reader(fieldname, coltype)
  524. if isinstance(creader, columns.TranslatingColumnReader):
  525. creader = creader.raw_column()
  526. cols[fieldname] = creader
  527. for docnum, stored in reader.iter_docs():
  528. if docmap is not None:
  529. docmap[docnum] = self.docnum
  530. pdw.start_doc(self.docnum)
  531. for fieldname in fieldnames:
  532. fieldobj = schema[fieldname]
  533. length = reader.doc_field_length(docnum, fieldname)
  534. pdw.add_field(fieldname, fieldobj,
  535. stored.get(fieldname), length)
  536. if fieldobj.vector and reader.has_vector(docnum, fieldname):
  537. v = reader.vector(docnum, fieldname, fieldobj.vector)
  538. pdw.add_vector_matcher(fieldname, fieldobj, v)
  539. if fieldname in cols:
  540. cv = cols[fieldname][docnum]
  541. pdw.add_column_value(fieldname, fieldobj.column_type, cv)
  542. pdw.finish_doc()
  543. self.docnum += 1
  544. return docmap
  545. def add_reader(self, reader):
  546. self._check_state()
  547. basedoc = self.docnum
  548. ndxnames = set(fname for fname in reader.indexed_field_names()
  549. if fname in self.schema)
  550. fieldnames = set(self.schema.names()) | ndxnames
  551. docmap = self.write_per_doc(fieldnames, reader)
  552. self.add_postings_to_pool(reader, basedoc, docmap)
  553. self._added = True
  554. def _check_fields(self, schema, fieldnames):
  555. # Check if the caller gave us a bogus field
  556. for name in fieldnames:
  557. if name not in schema:
  558. raise UnknownFieldError("No field named %r in %s"
  559. % (name, schema))
  560. def add_document(self, **fields):
  561. self._check_state()
  562. perdocwriter = self.perdocwriter
  563. schema = self.schema
  564. docnum = self.docnum
  565. add_post = self.pool.add
  566. docboost = self._doc_boost(fields)
  567. fieldnames = sorted([name for name in fields.keys()
  568. if not name.startswith("_")])
  569. self._check_fields(schema, fieldnames)
  570. perdocwriter.start_doc(docnum)
  571. for fieldname in fieldnames:
  572. value = fields.get(fieldname)
  573. if value is None:
  574. continue
  575. field = schema[fieldname]
  576. length = 0
  577. if field.indexed:
  578. # TODO: Method for adding progressive field values, ie
  579. # setting start_pos/start_char?
  580. fieldboost = self._field_boost(fields, fieldname, docboost)
  581. # Ask the field to return a list of (text, weight, vbytes)
  582. # tuples
  583. items = field.index(value)
  584. # Only store the length if the field is marked scorable
  585. scorable = field.scorable
  586. # Add the terms to the pool
  587. for tbytes, freq, weight, vbytes in items:
  588. weight *= fieldboost
  589. if scorable:
  590. length += freq
  591. add_post((fieldname, tbytes, docnum, weight, vbytes))
  592. if field.separate_spelling():
  593. spellfield = field.spelling_fieldname(fieldname)
  594. for word in field.spellable_words(value):
  595. word = utf8encode(word)[0]
  596. # item = (fieldname, tbytes, docnum, weight, vbytes)
  597. add_post((spellfield, word, 0, 1, vbytes))
  598. vformat = field.vector
  599. if vformat:
  600. analyzer = field.analyzer
  601. # Call the format's word_values method to get posting values
  602. vitems = vformat.word_values(value, analyzer, mode="index")
  603. # Remove unused frequency field from the tuple
  604. vitems = sorted((text, weight, vbytes)
  605. for text, _, weight, vbytes in vitems)
  606. perdocwriter.add_vector_items(fieldname, field, vitems)
  607. # Allow a custom value for stored field/column
  608. customval = fields.get("_stored_%s" % fieldname, value)
  609. # Add the stored value and length for this field to the per-
  610. # document writer
  611. sv = customval if field.stored else None
  612. perdocwriter.add_field(fieldname, field, sv, length)
  613. column = field.column_type
  614. if column and customval is not None:
  615. cv = field.to_column_value(customval)
  616. perdocwriter.add_column_value(fieldname, column, cv)
  617. perdocwriter.finish_doc()
  618. self._added = True
  619. self.docnum += 1
  620. def doc_count(self):
  621. return self.docnum - self.docbase
  622. def get_segment(self):
  623. newsegment = self.newsegment
  624. newsegment.set_doc_count(self.docnum)
  625. return newsegment
  626. def per_document_reader(self):
  627. if not self.perdocwriter.is_closed:
  628. raise Exception("Per-doc writer is still open")
  629. return self.codec.per_document_reader(self.storage, self.get_segment())
  630. # The following methods break out the commit functionality into smaller
  631. # pieces to allow MpWriter to call them individually
  632. def _merge_segments(self, mergetype, optimize, merge):
  633. # The writer supports two ways of setting mergetype/optimize/merge:
  634. # as attributes or as keyword arguments to commit(). Originally there
  635. # were just the keyword arguments, but then I added the ability to use
  636. # the writer as a context manager using "with", so the user no longer
  637. # explicitly called commit(), hence the attributes
  638. mergetype = mergetype if mergetype is not None else self.mergetype
  639. optimize = optimize if optimize is not None else self.optimize
  640. merge = merge if merge is not None else self.merge
  641. if mergetype:
  642. pass
  643. elif optimize:
  644. mergetype = OPTIMIZE
  645. elif not merge:
  646. mergetype = NO_MERGE
  647. else:
  648. mergetype = MERGE_SMALL
  649. # Call the merge policy function. The policy may choose to merge
  650. # other segments into this writer's pool
  651. return mergetype(self, self.segments)
  652. def _flush_segment(self):
  653. self.perdocwriter.close()
  654. if self.codec.length_stats:
  655. pdr = self.per_document_reader()
  656. else:
  657. pdr = None
  658. postings = self.pool.iter_postings()
  659. self.fieldwriter.add_postings(self.schema, pdr, postings)
  660. self.fieldwriter.close()
  661. if pdr:
  662. pdr.close()
  663. def _close_segment(self):
  664. if not self.perdocwriter.is_closed:
  665. self.perdocwriter.close()
  666. if not self.fieldwriter.is_closed:
  667. self.fieldwriter.close()
  668. self.pool.cleanup()
  669. def _assemble_segment(self):
  670. if self.compound:
  671. # Assemble the segment files into a compound file
  672. newsegment = self.get_segment()
  673. newsegment.create_compound_file(self.storage)
  674. newsegment.compound = True
  675. def _partial_segment(self):
  676. # For use by a parent multiprocessing writer: Closes out the segment
  677. # but leaves the pool files intact so the parent can access them
  678. self._check_state()
  679. self.perdocwriter.close()
  680. self.fieldwriter.close()
  681. # Don't call self.pool.cleanup()! We want to grab the pool files.
  682. return self.get_segment()
  683. def _finalize_segment(self):
  684. # Finish writing segment
  685. self._flush_segment()
  686. # Close segment files
  687. self._close_segment()
  688. # Assemble compound segment if necessary
  689. self._assemble_segment()
  690. return self.get_segment()
  691. def _commit_toc(self, segments):
  692. from whoosh.index import TOC, clean_files
  693. # Write a new TOC with the new segment list (and delete old files)
  694. toc = TOC(self.schema, segments, self.generation)
  695. toc.write(self.storage, self.indexname)
  696. # Delete leftover files
  697. clean_files(self.storage, self.indexname, self.generation, segments)
  698. def _finish(self):
  699. self._tempstorage.destroy()
  700. if self.writelock:
  701. self.writelock.release()
  702. self.is_closed = True
  703. #self.storage.close()
  704. # Finalization methods
  705. def commit(self, mergetype=None, optimize=None, merge=None):
  706. """Finishes writing and saves all additions and changes to disk.
  707. There are four possible ways to use this method::
  708. # Merge small segments but leave large segments, trying to
  709. # balance fast commits with fast searching:
  710. writer.commit()
  711. # Merge all segments into a single segment:
  712. writer.commit(optimize=True)
  713. # Don't merge any existing segments:
  714. writer.commit(merge=False)
  715. # Use a custom merge function
  716. writer.commit(mergetype=my_merge_function)
  717. :param mergetype: a custom merge function taking a Writer object and
  718. segment list as arguments, and returning a new segment list. If you
  719. supply a ``mergetype`` function, the values of the ``optimize`` and
  720. ``merge`` arguments are ignored.
  721. :param optimize: if True, all existing segments are merged with the
  722. documents you've added to this writer (and the value of the
  723. ``merge`` argument is ignored).
  724. :param merge: if False, do not merge small segments.
  725. """
  726. self._check_state()
  727. # Merge old segments if necessary
  728. finalsegments = self._merge_segments(mergetype, optimize, merge)
  729. if self._added:
  730. # Flush the current segment being written and add it to the
  731. # list of remaining segments returned by the merge policy
  732. # function
  733. finalsegments.append(self._finalize_segment())
  734. else:
  735. # Close segment files
  736. self._close_segment()
  737. # Write TOC
  738. self._commit_toc(finalsegments)
  739. # Final cleanup
  740. self._finish()
  741. def cancel(self):
  742. self._check_state()
  743. self._close_segment()
  744. self._finish()
  745. # Writer wrappers
  746. class AsyncWriter(threading.Thread, IndexWriter):
  747. """Convenience wrapper for a writer object that might fail due to locking
  748. (i.e. the ``filedb`` writer). This object will attempt once to obtain the
  749. underlying writer, and if it's successful, will simply pass method calls on
  750. to it.
  751. If this object *can't* obtain a writer immediately, it will *buffer*
  752. delete, add, and update method calls in memory until you call ``commit()``.
  753. At that point, this object will start running in a separate thread, trying
  754. to obtain the writer over and over, and once it obtains it, "replay" all
  755. the buffered method calls on it.
  756. In a typical scenario where you're adding a single or a few documents to
  757. the index as the result of a Web transaction, this lets you just create the
  758. writer, add, and commit, without having to worry about index locks,
  759. retries, etc.
  760. For example, to get an aynchronous writer, instead of this:
  761. >>> writer = myindex.writer()
  762. Do this:
  763. >>> from whoosh.writing import AsyncWriter
  764. >>> writer = AsyncWriter(myindex)
  765. """
  766. def __init__(self, index, delay=0.25, writerargs=None):
  767. """
  768. :param index: the :class:`whoosh.index.Index` to write to.
  769. :param delay: the delay (in seconds) between attempts to instantiate
  770. the actual writer.
  771. :param writerargs: an optional dictionary specifying keyword arguments
  772. to to be passed to the index's ``writer()`` method.
  773. """
  774. threading.Thread.__init__(self)
  775. self.running = False
  776. self.index = index
  777. self.writerargs = writerargs or {}
  778. self.delay = delay
  779. self.events = []
  780. try:
  781. self.writer = self.index.writer(**self.writerargs)
  782. except LockError:
  783. self.writer = None
  784. def reader(self):
  785. return self.index.reader()
  786. def searcher(self, **kwargs):
  787. from whoosh.searching import Searcher
  788. return Searcher(self.reader(), fromindex=self.index, **kwargs)
  789. def _record(self, method, args, kwargs):
  790. if self.writer:
  791. getattr(self.writer, method)(*args, **kwargs)
  792. else:
  793. self.events.append((method, args, kwargs))
  794. def run(self):
  795. self.running = True
  796. writer = self.writer
  797. while writer is None:
  798. try:
  799. writer = self.index.writer(**self.writerargs)
  800. except LockError:
  801. time.sleep(self.delay)
  802. for method, args, kwargs in self.events:
  803. getattr(writer, method)(*args, **kwargs)
  804. writer.commit(*self.commitargs, **self.commitkwargs)
  805. def delete_document(self, *args, **kwargs):
  806. self._record("delete_document", args, kwargs)
  807. def add_document(self, *args, **kwargs):
  808. self._record("add_document", args, kwargs)
  809. def update_document(self, *args, **kwargs):
  810. self._record("update_document", args, kwargs)
  811. def add_field(self, *args, **kwargs):
  812. self._record("add_field", args, kwargs)
  813. def remove_field(self, *args, **kwargs):
  814. self._record("remove_field", args, kwargs)
  815. def delete_by_term(self, *args, **kwargs):
  816. self._record("delete_by_term", args, kwargs)
  817. def commit(self, *args, **kwargs):
  818. if self.writer:
  819. self.writer.commit(*args, **kwargs)
  820. else:
  821. self.commitargs, self.commitkwargs = args, kwargs
  822. self.start()
  823. def cancel(self, *args, **kwargs):
  824. if self.writer:
  825. self.writer.cancel(*args, **kwargs)
  826. # Ex post factor functions
  827. def add_spelling(ix, fieldnames, commit=True):
  828. """Adds spelling files to an existing index that was created without
  829. them, and modifies the schema so the given fields have the ``spelling``
  830. attribute. Only works on filedb indexes.
  831. >>> ix = index.open_dir("testindex")
  832. >>> add_spelling(ix, ["content", "tags"])
  833. :param ix: a :class:`whoosh.filedb.fileindex.FileIndex` object.
  834. :param fieldnames: a list of field names to create word graphs for.
  835. :param force: if True, overwrites existing word graph files. This is only
  836. useful for debugging.
  837. """
  838. from whoosh.automata import fst
  839. from whoosh.reading import SegmentReader
  840. writer = ix.writer()
  841. storage = writer.storage
  842. schema = writer.schema
  843. segments = writer.segments
  844. for segment in segments:
  845. ext = segment.codec().FST_EXT
  846. r = SegmentReader(storage, schema, segment)
  847. f = segment.create_file(storage, ext)
  848. gw = fst.GraphWriter(f)
  849. for fieldname in fieldnames:
  850. gw.start_field(fieldname)
  851. for word in r.lexicon(fieldname):
  852. gw.insert(word)
  853. gw.finish_field()
  854. gw.close()
  855. for fieldname in fieldnames:
  856. schema[fieldname].spelling = True
  857. if commit:
  858. writer.commit(merge=False)
  859. # Buffered writer class
  860. class BufferedWriter(IndexWriter):
  861. """Convenience class that acts like a writer but buffers added documents
  862. before dumping the buffered documents as a batch into the actual index.
  863. In scenarios where you are continuously adding single documents very
  864. rapidly (for example a web application where lots of users are adding
  865. content simultaneously), using a BufferedWriter is *much* faster than
  866. opening and committing a writer for each document you add. If you're adding
  867. batches of documents at a time, you can just use a regular writer.
  868. (This class may also be useful for batches of ``update_document`` calls. In
  869. a normal writer, ``update_document`` calls cannot update documents you've
  870. added *in that writer*. With ``BufferedWriter``, this will work.)
  871. To use this class, create it from your index and *keep it open*, sharing
  872. it between threads.
  873. >>> from whoosh.writing import BufferedWriter
  874. >>> writer = BufferedWriter(myindex, period=120, limit=20)
  875. >>> # Then you can use the writer to add and update documents
  876. >>> writer.add_document(...)
  877. >>> writer.add_document(...)
  878. >>> writer.add_document(...)
  879. >>> # Before the writer goes out of scope, call close() on it
  880. >>> writer.close()
  881. .. note::
  882. This object stores documents in memory and may keep an underlying
  883. writer open, so you must explicitly call the
  884. :meth:`~BufferedWriter.close` method on this object before it goes out
  885. of scope to release the write lock and make sure any uncommitted
  886. changes are saved.
  887. You can read/search the combination of the on-disk index and the
  888. buffered documents in memory by calling ``BufferedWriter.reader()`` or
  889. ``BufferedWriter.searcher()``. This allows quasi-real-time search, where
  890. documents are available for searching as soon as they are buffered in
  891. memory, before they are committed to disk.
  892. .. tip::
  893. By using a searcher from the shared writer, multiple *threads* can
  894. search the buffered documents. Of course, other *processes* will only
  895. see the documents that have been written to disk. If you want indexed
  896. documents to become available to other processes as soon as possible,
  897. you have to use a traditional writer instead of a ``BufferedWriter``.
  898. You can control how often the ``BufferedWriter`` flushes the in-memory
  899. index to disk using the ``period`` and ``limit`` arguments. ``period`` is
  900. the maximum number of seconds between commits. ``limit`` is the maximum
  901. number of additions to buffer between commits.
  902. You don't need to call ``commit()`` on the ``BufferedWriter`` manually.
  903. Doing so will just flush the buffered documents to disk early. You can
  904. continue to make changes after calling ``commit()``, and you can call
  905. ``commit()`` multiple times.
  906. """
  907. def __init__(self, index, period=60, limit=10, writerargs=None,
  908. commitargs=None):
  909. """
  910. :param index: the :class:`whoosh.index.Index` to write to.
  911. :param period: the maximum amount of time (in seconds) between commits.
  912. Set this to ``0`` or ``None`` to not use a timer. Do not set this
  913. any lower than a few seconds.
  914. :param limit: the maximum number of documents to buffer before
  915. committing.
  916. :param writerargs: dictionary specifying keyword arguments to be passed
  917. to the index's ``writer()`` method when creating a writer.
  918. """
  919. self.index = index
  920. self.period = period
  921. self.limit = limit
  922. self.writerargs = writerargs or {}
  923. self.commitargs = commitargs or {}
  924. self.lock = threading.RLock()
  925. self.writer = self.index.writer(**self.writerargs)
  926. self._make_ram_index()
  927. self.bufferedcount = 0
  928. # Start timer
  929. if self.period:
  930. self.timer = threading.Timer(self.period, self.commit)
  931. self.timer.start()
  932. def __exit__(self, exc_type, exc_val, exc_tb):
  933. self.close()
  934. def _make_ram_index(self):
  935. from whoosh.codec.memory import MemoryCodec
  936. self.codec = MemoryCodec()
  937. def _get_ram_reader(self):
  938. return self.codec.reader(self.schema)
  939. @property
  940. def schema(self):
  941. return self.writer.schema
  942. def reader(self, **kwargs):
  943. from whoosh.reading import MultiReader
  944. reader = self.writer.reader()
  945. with self.lock:
  946. ramreader = self._get_ram_reader()
  947. # If there are in-memory docs, combine the readers
  948. if ramreader.doc_count():
  949. if reader.is_atomic():
  950. reader = MultiReader([reader, ramreader])
  951. else:
  952. reader.add_reader(ramreader)
  953. return reader
  954. def searcher(self, **kwargs):
  955. from whoosh.searching import Searcher
  956. return Searcher(self.reader(), fromindex=self.index, **kwargs)
  957. def close(self):
  958. self.commit(restart=False)
  959. def commit(self, restart=True):
  960. if self.period:
  961. self.timer.cancel()
  962. with self.lock:
  963. ramreader = self._get_ram_reader()
  964. self._make_ram_index()
  965. if self.bufferedcount:
  966. self.writer.add_reader(ramreader)
  967. self.writer.commit(**self.commitargs)
  968. self.bufferedcount = 0
  969. if restart:
  970. self.writer = self.index.writer(**self.writerargs)
  971. if self.period:
  972. self.timer = threading.Timer(self.period, self.commit)
  973. self.timer.start()
  974. def add_reader(self, reader):
  975. # Pass through to the underlying on-disk index
  976. self.writer.add_reader(reader)
  977. self.commit()
  978. def add_document(self, **fields):
  979. with self.lock:
  980. # Hijack a writer to make the calls into the codec
  981. with self.codec.writer(self.writer.schema) as w:
  982. w.add_document(**fields)
  983. self.bufferedcount += 1
  984. if self.bufferedcount >= self.limit:
  985. self.commit()
  986. def update_document(self, **fields):
  987. with self.lock:
  988. IndexWriter.update_document(self, **fields)
  989. def delete_document(self, docnum, delete=True):
  990. with self.lock:
  991. base = self.index.doc_count_all()
  992. if docnum < base:
  993. self.writer.delete_document(docnum, delete=delete)
  994. else:
  995. ramsegment = self.codec.segment
  996. ramsegment.delete_document(docnum - base, delete=delete)
  997. def is_deleted(self, docnum):
  998. base = self.index.doc_count_all()
  999. if docnum < base:
  1000. return self.writer.is_deleted(docnum)
  1001. else:
  1002. return self._get_ram_reader().is_deleted(docnum - base)
  1003. # Backwards compatibility with old name
  1004. BatchWriter = BufferedWriter