2012-02-06

Is your IndexReader atomic? - Major IndexReader refactoring in Lucene 4.0

Note: This blog post was originally posted on the SearchWorkings website.

Since Day 1 Lucene exposed the two fundamental concepts of reading and writing an index directly through IndexReader & IndexWriter. However, the API didn’t reflect reality; from the IndexWriter perspective this was desirable but when reading the index this caused several problems in the past. In reality a Lucene index isn’t a single index while logically treated as a such. The latest developments in Lucene trunk try to expose reality for type-safety and performance, but before I go into details about Composite, Atomic and DirectoryReaders let me go back in time a bit.

Since version 2.9 / 3.0 Lucene started to move away from executing searches directly on the top-level IndexReaders towards a per-segment orientation. As Simon Willnauer already explained in his blog entry, this lead to fact that optimizing an index is no longer needed to optimize searching performance. In fact, optimizing would slow your searches down, as after optimizing, all file system and Lucene-internal index caches get invalidated.

A standard Lucene index consists of several so-called segments, which are themselves fully-functional Lucene indexes. During indexing, Lucene writes new documents into separate segments and, once there are too many segments, they are merged. (see Mike McCandless’ blog: Visualizing Lucene's segment merges):



Prior to Lucene 2.9, despite consisting of multiple underlying segments, the segments were treated as though they were a single big index. Since then, Lucene has shifted towards a per-segment orientation. By now almost all structures and components in Lucene operate on a per-segment basis; among others this means that Lucene only loads actual changes on reopen, instead of the entire index. From a users perspective it might still look like one big logical index but under the hood everything works per-segment like this (simplified) IndexSearcher snippet shows:
 public void search(Weight weight, Collector collector) throws IOException {  
  // iterate through all segment readers & execute the search  
  for (int i = 0; i < subReaders.length; i++) {  
   // pass the reader to the collector  
   collector.setNextReader(subReaders[i], docStarts[i]);  
   final Scorer scorer = ...;  
   if (scorer != null) { // score documents on this segment  
    scorer.score(collector);  
   }  
  }  
 }  
However, the distinction between a logical index and a segment wasn’t consistently reflected in the code hierarchy. In Lucene 3.x, one could still execute searches on a top-level (logical) reader, without iterating over its subreaders. Doing so could slowdown your searches dramatically provided your index consisted of more than one segment. Among other reasons, this was why ancient versions of Lucene instructed users to optimize the index frequently.

Let me explain the problem in a little more detail. An IndexReader on top of a Directory is internally a MultiReader on all enclosing SegmentReaders. If you ask a MultiReader for a TermEnum or the Postings it executes an on-the-fly merge all of all subreader’s terms or postings data respectively. This merge process uses priority queues or related data structures leading to a serious slowdown depending on the number of subreaders.

Yet, even beyond these internal limitations using SegmentReaders in combination with MultiReaders can influence higher-level structures in Lucene. The FieldCache is used to uninvert the index to allow sorting of search results by indexed value or Document / Value lookups during search. Uninverting the top-level readers leads to duplication in the FieldCache and essentially multiple instances of the same cache.

Type-Safe IndexReaders in Lucene 4.0

From day one Lucene 4.0 was designed to not allow retrieving of terms and postings data from “composite” readers like MultiReader or DirectoryReader (which is the implementation that is returned for on-disk indexes, if you get a reader from IndexReader.open(Directory)). Initial versions of Lucene trunk simply threw an UnsupportedOperationException when you tried to get instances of Fields, TermsEnum, or DocsEnum from a non SegmentReader. Because of the missing type safety, one couldn’t rely on the ability to get postings from the IndexReader unless manually checking if it was composite or atomic.

LUCENE-2858 is one of the major API changes in Lucene 4.0, it completely changes the Lucene client code “perspective” on indexes and its segments. The abstract class IndexReader has been refactored to expose only essential methods to access stored fields during display of search results. It is no longer possible to retrieve terms or postings data from the underlying index, not even deletions are visible anymore. You can still pass IndexReader as constructor parameter to IndexSearcher and execute your searches; Lucene will automatically delegate procedures like query rewriting and document collection atomic subreaders.

If you want to dive deeper into the index and want to write own queries, take a closer look at the new abstract sub-classes AtomicReader and CompositeReader:

AtomicReader instances are now the only source of Terms, Postings, DocValues and FieldCache. Queries are forced to execute on a Atomic reader on a per-segment basis and FieldCaches are keyed by AtomicReaders. It’s counterpart CompositeReader exposes a utility method to retrieve its composites. But watch out, composites are not necessarily atomic. Next to the added type-safety we also removed the notion of index-commits and version numbers from the abstract IndexReader, the associations with IndexWriter were pulled into a specialized DirectoryReader. Here is an “example” executing a query in Lucene trunk:
 DirectoryReader reader = DirectoryReader.open(directory);  
 IndexSearcher searcher = new IndexSearcher(reader);  
 Query query = new QueryParser("fieldname", analyzer).parse(“text”);  
 TopDocs hits = searcher.search(query, 10);  
 ScoreDoc[] docs = hits.scoreDocs;  
 Document doc1 = searcher.doc(docs[0].doc);  
 // alternative:  
 Document doc2 = reader.document(docs[1].doc);  
Does that look familiar? Well, for the actual API user this major refactoring doesn’t bring much of a change. If you run into compile errors related to this change while upgrading you likely found a performance bottleneck.

Enforcing Per-Segment semantics in Filters

If you have more advanced code dealing with custom Filters, you might have noticed another new class hierarchy in Lucene (see LUCENE-2831): IndexReaderContext with corresponding Atomic-/CompositeReaderContext. This has been added quite a while ago but is closely related to atomic and composite readers.

The move towards per-segment search Lucene 2.9 exposed lots of custom Queries and Filters that couldn't handle it. For example, some Filter implementations expected the IndexReader passed in is identical to the IndexReader passed to IndexSearcher with all its advantages like absolute document IDs etc. Obviously this “paradigm-shift” broke lots of applications and especially those that utilized cross-segment data structures (like Apache Solr).

In Lucene 4.0, we introduce IndexReaderContexts “searcher-private” reader hierarchy. During Query or Filter execution Lucene no longer passes raw readers down Queries, Filters or Collectors; instead components are provided an AtomicReaderContext (essentially a hierarchy leaf) holding relative properties like the document-basis in relation to the top-level reader. This allows Queries & Filter to build up logic based on document IDs, albeit the per-segment orientation.

Can I still use top-level readers?

There are still valid use-cases where Top-Level readers ie. “atomic views” on the index are desirable. Let say you want to iterate all terms of a complete index for auto-completion or facetting, Lucene provides utility wrappers like SlowCompositeReaderWrapper emulating an AtomicReader. Note: using “atomicity emulators” can cause serious slowdowns due to the need to merge terms, postings, DocValues, and FieldCache, use them with care!
 Terms terms = SlowCompositeReaderWrapper.wrap(directoryReader).terms(“field”);  
Unfortunately, Apache Solr still uses this horrible code in a lot of places, leaving us with a major piece of work undone. Major parts of Solr’s facetting and filter caching need to be rewritten to work per atomic segment! For those implementing plugins or other components for Solr, SolrIndexSearcher exposes a “atomic view” of its underlying reader via SolrIndexSearcher.getAtomicReader().

If you want to write memory-effective and fast search applications (that do not need those useless large caches like Solr uses), I would recommend to not use Solr 4.0 and instead write your search application around the new Lucene components like the new facet module and SearcherManager!

45 comments:

  1. Thank you for this piece of vital and totally undocumented knowledge!

    I still don't quite understand what else I can use rather than SlowCompositeReaderWrapper in case I want to retrieve a field for all the documents in the index via FieldCache.
    By the way, I didn't force Lucene to build several segments, the entire index was static from the very first indexing. Still, there are multiple segments in it.

    ReplyDelete
  2. quote. Thank you for this piece of vital...knowledge!" quote.

    Absolutely. Thank you so much. I'm upgrading some legacy code from 2.0.0 to 4.2.0 and it is non trivial to find this kind of stuff out without hitting the bottle in the process. This has saved me a major hangover.

    ReplyDelete
  3. Hi Uwe,

    Do you have any insight for MultiReader, which is a CompositeReader?

    I am using it not just for search but also MoreLikeThis constructor and HighFreqTerms.getHighFreqTerms(IndexReader reader, int numTerms, String field). Is it safe to assume the statistics returned are from across all sub readers in the MultiReaders?

    Also I have a challenge.

    We are upgrading from Lucene 2.9.4 to 4.3. We used to use a ParallelMultiSearcher with an array Searchables. These Searchables were heterogeneous. Some were IndexSearchers made from local directories, some were remote searchers via web services, and some were Solr searcher clients using solrj.jar. We did use and do not plan to use Solr sever at all. Since the Searchable interface is deprecated, what will be our work around to accommodate our heterogeneous searchers?

    Thanks!

    ReplyDelete
  4. 먹튀사이트 잡는 고릴라의 먹튀검증 통과 메이저토토사이트 안전놀이터 추천 훌륭한 먹튀검증을 통한 안전토토사이트를 추천합니다 고릴라만의 검증 시스템은 특별합니다 전세계적인 먹튀검증을 인전받은 최고의 메이저사이트 추천을 합니다 자세한 내용은 내 웹 사이트를 방문하십시오 토토사이트.

    ReplyDelete
  5. This is much safer and smarter for everyone. We

    ReplyDelete
  6. The United Kingdom meds area unit thorough in their reviewable my consultations and meds were sent promptly. I might advocate them to anybody World Health Organization desires to require on-line consultations from the site https://deutschemedz.de. I'll use them within the future.

    ReplyDelete
  7. The function of rotor stator pumps is basically very simple Feuerfest. The screw, the metallic rotor, rotates and seals the conveying chambers on the inside of the stator.

    ReplyDelete
  8. Rufen Sie uns an! Wir nehmen Ihnen die harte Arbeit ab.
    Wir bieten professionelle Haushaltsauflösungen/ Entrümpelungen von Häusern, Wohnungen, Dachböden, Kellerräumen, Garagen, Gärten und anderen Objekten. Zudem bieten wir Seniorenumzüge, Möbeltransporte und Entsorgungsfahrten.
    RümpelRuder ist Ihr starker Partner in Hannover und Umgebung. Haushaltsauflösung Hannover

    ReplyDelete
  9. Eurokraut ist der beste Ort in Europa, um Weed online kaufen. Wir verkaufen erstklassiges Cannabis zu erschwinglichen Preisen für unsere geschätzten Kunden. Schauen Sie sich jetzt unsere beliebten Cannabissorten an und bestellen Sie noch heute. Weed online kaufen

    ReplyDelete

  10. Essbare Insekten kaufen - in unserem Onlineshop so leicht wie nie! Insekten kaufen ist eine leckere Angelegenheit, denn Insekten beinhalten viel Proteine und andere wichtige Nährstoffe, Omega-3-Fettsäuren, Vitamine und Antioxidatien. Insekten


    ReplyDelete
  11. With the https://kreditxxl.de/ loan comparison you will find the cheapest financing offer for your personal project in no time. Online Kredit aufnehmen

    ReplyDelete
  12. Günstige Medikamente von namhaften Herstellern gibt es bei Meddirekt 24. Mein persönlicher Favorit ist Priligy Dapoxetin. Aber es gibt noch viele andere Medikamente im Sortiment, so dass jeder Besucher finden kann, was er braucht.

    ReplyDelete




  13. Bitte beachten Sie unbedingt unsere Hinweise zur korrekten Adressierung Ihrer Sendung und zur richtigen Zahlart. Bitte beachten Sie auch, dass MeinEinkauf.ch gewisse Waren nicht in die Schweiz liefern kann. Fightwear



    ReplyDelete


  14. InfoVIN ist einer der führenden Lieferanten von Berichten über Historie der Gebrauchtfahrzeuge aus Europa und aus den USA. Nutzen Sie unser Wissen und unsere Erfahrung, die Ihnen die Überprüfung der Fahrzeughistorie ermöglichen. www.infovin.de

    ReplyDelete
  15. Unsere Webdesign-Mietpakete haben alles, was Sie brauchen, um Ihr Unternehmen online zu bringen, ohne Ihr Bankkonto zu sprengen. Wenn Sie sich für eines unserer Webseite-Mietpakete entscheiden, können Sie Ihre Webseite monatlich bezahlen. Das bedeutet, dass keine grossen Kosten für die Entwicklung Ihrer Webseite sowie keine laufenden Kosten für die Wartung, Aktualisierung und das Hosting anfallen. webdesign


    ReplyDelete


  16. Willkommen bei Bokma Dienstleistungen GmbH, Ihre Gebäudereinigung in Nürnberg und Umgebung. gebäudereinigung nürnberg

    ReplyDelete

  17. LINA GRAU PAPAGEI bildet seit mehr als 10 Jahren Papageien aus und züchtet sie. Wir haben den Kongo und Timneh Grau Papagei gezüchtet und aufgezogen, die die meiste Zeit unseres Lebens. graupapagei kaufen

    ReplyDelete

  18. Wir sind ein 100% ungarisches Unternehmen mit langjähriger Erfahrung in der Reparatur von Industrieelektronik. Die Geschäftsphilosophie von COWARE basiert auf fairem Geschäft und menschlichem Verhalten, einer umfassenden Aufdeckung und Ermessung der Bedürfnisse unserer Kunden und der einwandfreien Einhaltung von Fristen und vertraglichen Verpflichtungen. industrieelektronik reparatur

    ReplyDelete

  19. Entdecke traumhafte Luftballons und stilvolle Deko bei BallonStar® Wir sind stetig auf der Suche nach trendigen Luftballons sowie Partydeko für dein Event. Finde eindrucksvolle Luftballons aus Folie Ballonstar.de, Airloonz, Airwalker, Walking Balloons, 4D Ballons und vieles mehr - Jetzt entdecken. Ballongas

    ReplyDelete
  20. Fuhrerschein-online.net is a German website specializing in the production of German, Austrian, Swiss and EU driving licenses. deutschen führerschein kaufen

    ReplyDelete

  21. Geschenke zur Erinnerung | Aus der alten Kiste zur neuen Erinnerung | Nur weil es ein altes Kleidungsstück ist, muss es nicht in einer alten Kiste im Schrank verstaut und vergessen werden. babywolldecke


    ReplyDelete
  22. Bei uns erhalten Sie Backlink Pakete für eine erfolgreiche SEO. Ein Backlink ist ein Rückverweis (englisch: Backlink) bezeichnet einen Link, der von einer anderen Website auf die eigene Seite führt. Backlinks sind ein entscheidender Erfolgsfaktor für eine gute Position in Suchmaschinenergebnissen (search engine result pages; SERPS). links kaufen

    ReplyDelete

  23. Wir erstellen Ihre individuelle Webseite, die auf allen Endgeräten super aussehen wird – und das schon ab 599,- €. Unser Know-How und unsere Kreativität sind unsere Stärken. Webdesigner


    ReplyDelete
  24. Aus Gesprächen mit diversen Kollegen machte ich mir über meine finanzielle Situation Gedanken. Schnell stellte ich fest, dass ich die Finanzen optimieren könnte, wenn ich auch wollte. Geld investieren

    ReplyDelete
  25. Bei Dekostyl Onlineshop dreht sich alles um hochwertige und nachhaltige Produkte und das Erschaffen einer exklusiven Atmosphäre. Wir haben uns zum Ziel gemacht, Wandpaneele, Dekorationselemente und Couchtische aus Echtholz zu bezahlbaren Preisen erhältlich zu machen. Wandpaneele 3D aus Holz

    ReplyDelete

  26. Wir sind ein europäisches Unternehmen, das sich auf Handyersatzteile spezialisiert hat. Wir haben unser Hobby zum Beruf gemacht. Alle unsere Produkte sind auch von uns selbst geprüft. Wir legen großen Wert auf Qualität und Schnelligkeit. Bei Fragen und Anregungen stehen wir Ihnen gerne per Email oder telefonisch zur Verfügung! Iphone 12 akku

    ReplyDelete
  27. Auf unserer Homepage haben wir für Dich die größten und besten Datingseiten und Singlebörsen im Internet getestet. In der heutigen Zeit wird das Thema Onlinedating immer wichtiger und bekommt immer größere Bedeutung. Da jeden Tag weitere Online-Dating. Datingportal

    ReplyDelete
  28. Mein neues Projekt behandelt das ganze Spektrum dessen, was die Börse zu bieten hat. Es geht um Analagestrategien, um ETFs, um Aktien, um technische Analyse und Börsenpsychologie. Das Wissen, welches ich in den letzten 15 Jahren an der Börse gesammelt habe, wird auf der neuen Seite zur Verfügung gestellt und kontinuierlich erweitert. Börsencrash 2022

    ReplyDelete

  29. LikeMeASAP bietet Ihnen hochwertige Erklärvideos für Ihr Unternehmen. Gewinnen Sie Neukunden durch ein professionelles Erklärvideo. erklärvideo

    ReplyDelete

  30. Hallo an alle, es ist mein erster Besuch dieser Webseite; Diese Website enthält erstaunliches und wirklich gutes Material für Leser. Pornodarstellerin werden

    ReplyDelete
  31. Dies ist ein ausgezeichneter Beitrag, den ich dank Teilen gesehen habe. Es ist wirklich das, was ich sehen wollte, und hoffe, dass Sie in Zukunft weiterhin einen so hervorragenden Beitrag teilen werden. Autowerkstatt

    ReplyDelete
  32. Verhindere ein Blackout mit einem eigenen Stromgenerator oder Batteriespeicher. Stromgenerator kaufen

    ReplyDelete
  33. Very nice and very important post thank you so much for sharing.
    Abogado De Trafico En Virginia

    ReplyDelete
  34. kingdom66 ทาง เข้า เว็บไซต์พนันออนไลน์ ชั้น 1 คาสิโนสด สล็อตออนไลน์ pg slot และก็พนันกีฬาต่างๆฝาก-ถอน Auto เพียงแต่ 30 วินาที โปรโมชั่นพิเศษ โบนัสต่างๆมากมายก่ายกองที่สุด

    ReplyDelete
  35. t6158 สล็อต เป็นเว็บสล็อตออนไลน์ระดับ 1 ที่เติบโตอย่างใหญ่โตในท้องที่ทวีปเอเชีย pg slot แล้วหลังจากนั้นก็เป็นตัวเลือกป้อมบางทีอาจแล้วก็น่าเชื่อถือสำหรับผู้เล่นที่กำลังมองหาประสบการณ์

    ReplyDelete
  36. sierra 88 slot wallet เว็บไซต์พนันออนไลน์ที่ดิน พวกเรา pg slot ได้ปรับปรุงระบบการเล่น แล้วก็แบบเกมที่เป็นต้นแบบที่นำสมัย แล้วก็ระบบที่อัพเดทมาก็มีความแปลกใหม่อยู่เสมอเวลา

    ReplyDelete
  37. ks888 pg สล็อตพีจีออนไลน์ ที่รองรับ การใช้แรงงานผ่านมือถือ pg slot แล้วก็สมาร์ตโฟน ทุกระบบ รองรับภาษาไทย ทำให้เล่นง่าย ใช้งานสบาย นอกเหนือจากนี้ยังสามารถ ใช้งานเล่นได้อีก

    ReplyDelete
  38. "Your blog is an absolute goldmine of inspiration and insightful information on The Generics Policeman Blog: Is your IndexReader atomic. I genuinely appreciate the valuable insights you share. Your passion for this subject is clearly reflected in your thoughtful posts, making each visit a truly enriching experience."Abogado de Violencia Doméstica New JerseyDivorcio Barato en Nueva York

    ReplyDelete
  39. The Lucene 4.0 update marks a major leap with a revamped IndexReader, ensuring atomicity in its operations, providing developers with enhanced reliability and consistency in managing indices. This significant refactoring underscores Lucene's commitment to robustness and streamlined functionality for efficient information retrieval.||Is there A Waiting Period for Divorce in New York||Is New York A No Fault State for Divorce

    ReplyDelete
  40. A reliable source of valuable information!
    splunk course

    ReplyDelete
  41. The comment "is-your-indexreader-atomic-major" can be interpreted in various ways, such as checking the reader type, reviewing code related to atomicity, or as a general reminder. In search engines like Lucene, it could be a question about the type of IndexReader, which can be crucial for performance optimizations. It could also be a note from a developer to remind others about the importance of atomicity, especially when dealing with multi-segment indexes.
    motorcycle accident attorney

    ReplyDelete
  42. ติดต่อเรา pg slot เว็บตรง ลูกค้าสามารถ ติดต่อมาและสอบถาม เนื้อหาการใช้แรงงานได้ทาง PG SLOT หรืออยากได้ อัพเดทข้อมูลโปรโมชั่นใหม่ ลูกค้าก็สามารถแอดไลน์ เพื่อติดตามข้อมูลได้ในทันที

    ReplyDelete
  43. The blog you shared provides insightful information on the atomicity of IndexReader. It's a valuable resource for understanding this concept deeply. I appreciate the clarity and depth of explanation provided in the post. This blog has certainly enriched my understanding of IndexReader's atomic behavior.
    Registro Central Violencia Doméstica Nueva Jersey
    Domestic Violence Registry New Jersey

    ReplyDelete