Package org.apache.lucene.search

Examples of org.apache.lucene.search.SearcherManager


  private final SearcherManager mgr;

  public SimpleSearcher(final File path) throws IOException {
    dir = FSDirectory.open(path);
    mgr = new SearcherManager(dir, null);
  }
View Full Code Here


            searcherManager = null;
        }

        this.indexWriter = new NexusIndexWriter( getIndexDirectory(), getWriterConfig() );
        this.indexWriter.commit(); // LUCENE-2386
        this.searcherManager = new SearcherManager( indexWriter, false, new NexusIndexSearcherFactory( this ) );
    }
View Full Code Here

    BooleanQuery query = new BooleanQuery();
    Term waveIdTerm = new Term(WAVEID.toString(), wavelet.getWaveId().serialise());
    query.add(new TermQuery(waveIdTerm), BooleanClause.Occur.MUST);
    query.add(new TermQuery(new Term(WAVELETID.toString(), wavelet.getWaveletId().serialise())),
        BooleanClause.Occur.MUST);
    SearcherManager searcherManager = nrtManager.getSearcherManager(true);
    IndexSearcher indexSearcher = searcherManager.acquire();
    try {
      TopDocs hints = indexSearcher.search(query, MAX_WAVES);
      for (ScoreDoc hint : hints.scoreDocs) {
        Document document = indexSearcher.doc(hint.doc);
        String[] participantValues = document.getValues(WITH.toString());
        document.removeFields(WITH.toString());
        for (String address : participantValues) {
          if (address.equals(participant.getAddress())) {
            continue;
          }
          document.add(new Field(WITH.toString(), address, Field.Store.YES,
              Field.Index.NOT_ANALYZED));
        }
        nrtManager.updateDocument(waveIdTerm, document);
      }
    } catch (IOException e) {
      LOG.log(Level.WARNING, "Failed to fetch from index " + wavelet.toString(), e);
    } finally {
      try {
        searcherManager.release(indexSearcher);
      } catch (IOException e) {
        LOG.log(Level.WARNING, "Failed to close searcher. ", e);
      }
      indexSearcher = null;
    }
View Full Code Here

    Preconditions.checkNotNull(user);

    Multimap<WaveId, WaveletId> userWavesViewMap = HashMultimap.create();
    BooleanQuery participantQuery = new BooleanQuery();
    participantQuery.add(new TermQuery(new Term(WITH.toString(), user.getAddress())), Occur.SHOULD);
    SearcherManager searcherManager = nrtManager.getSearcherManager(true);
    IndexSearcher indexSearcher = searcherManager.acquire();
    try {
      TopDocs hints = indexSearcher.search(participantQuery, MAX_WAVES, LMT_ASC_SORT);
      for (ScoreDoc hint : hints.scoreDocs) {
        Document document = indexSearcher.doc(hint.doc);
        WaveId waveId = WaveId.deserialise(document.get(WAVEID.toString()));
        WaveletId waveletId = WaveletId.deserialise(document.get(WAVELETID.toString()));
        userWavesViewMap.put(waveId, waveletId);
      }
    } catch (IOException e) {
      LOG.log(Level.WARNING, "Search failed: " + user, e);
    } finally {
      try {
        searcherManager.release(indexSearcher);
      } catch (IOException e) {
        LOG.log(Level.WARNING, "Failed to close searcher. " + user, e);
      }
      indexSearcher = null;
    }
View Full Code Here

    if (DirectoryReader.indexExists(dir)) {
      // Already built; open it:
      writer = new IndexWriter(dir,
                               getIndexWriterConfig(matchVersion, getGramAnalyzer(), IndexWriterConfig.OpenMode.APPEND));
      searcherMgr = new SearcherManager(writer, true, null);
    }
  }
View Full Code Here

        add(text, iter.contexts(), iter.weight(), payload);
      }

      //System.out.println("initial indexing time: " + ((System.nanoTime()-t0)/1000000) + " msec");

      searcherMgr = new SearcherManager(writer, true, null);
      success = true;
    } finally {
      if (success) {
        IOUtils.close(r);
      } else {
View Full Code Here

      locks[i] = new Object();
    }

    final AtomicLong nextVersion = new AtomicLong();

    final SearcherManager mgr = new SearcherManager(w.w, true, new SearcherFactory());

    final Long missingValue = -1L;

    final LiveFieldValues<IndexSearcher,Long> versionValues = new LiveFieldValues<IndexSearcher,Long>(mgr, missingValue) {
      @Override
      protected Long lookupFromSearcher(IndexSearcher s, String id) {
        // TODO: would be cleaner if we could do our PerThreadLookup here instead of "up above":
        // We always return missing: the caller then does a lookup against the current reader
        return missingValue;
      }
    };

    // Maps to the version the id was lasted indexed with:
    final Map<String,Long> truth = new ConcurrentHashMap<>();

    final CountDownLatch startingGun = new CountDownLatch(1);

    Thread[] threads = new Thread[TestUtil.nextInt(random(), 2, 7)];

    final int versionType = random().nextInt(3);

    if (VERBOSE) {
      if (versionType == 0) {
        System.out.println("TEST: use random versions");
      } else if (versionType == 1) {
        System.out.println("TEST: use monotonic versions");
      } else {
        System.out.println("TEST: use nanotime versions");
      }
    }

    // Run for 3 sec in normal tests, else 60 seconds for nightly:
    final long stopTime = System.currentTimeMillis() + (TEST_NIGHTLY ? 60000 : 3000);

    for(int i=0;i<threads.length;i++) {
      threads[i] = new Thread() {
          @Override
          public void run() {
            try {
              runForReal();
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }

          private void runForReal() throws IOException, InterruptedException {
            startingGun.await();
            PerThreadVersionPKLookup lookup = null;
            IndexReader lookupReader = null;
            while (System.currentTimeMillis() < stopTime) {

              // Intentionally pull version first, and then sleep/yield, to provoke version conflicts:
              long newVersion;
              if (versionType == 0) {
                // Random:
                newVersion = random().nextLong() & 0x3fffffffffffffffL;
              } else if (versionType == 1) {
                // Monotonic
                newVersion = nextVersion.getAndIncrement();
              } else {
                newVersion = System.nanoTime();
              }

              if (versionType != 0) {
                if (random().nextBoolean()) {
                  Thread.yield();
                } else {
                  Thread.sleep(TestUtil.nextInt(random(), 1, 4));
                }
              }

              int x = random().nextInt(ids.length);

              // TODO: we could relax this, if e.g. we assign indexer thread based on ID.  This would ensure a given ID cannot be indexed at
              // the same time in multiple threads:

              // Only one thread can update an ID at once:
              synchronized (locks[x]) {

                String id = ids[x];

                // We will attempt to index id with newVersion, but only do so if id wasn't yet indexed, or it was indexed with an older
                // version (< newVersion):

                // Must lookup the RT value before pulling from the index, in case a reopen happens just after we lookup:
                Long currentVersion = versionValues.get(id);

                IndexSearcher s = mgr.acquire();
                try {
                  if (VERBOSE) System.out.println("\n" + Thread.currentThread().getName() + ": update id=" + id + " newVersion=" + newVersion);

                  if (lookup == null || lookupReader != s.getIndexReader()) {
                    // TODO: sort of messy; we could add reopen to PerThreadVersionPKLookup?
                    // TODO: this is thin ice .... that we don't incRef/decRef this reader we are implicitly holding onto:
                    lookupReader = s.getIndexReader();
                    if (VERBOSE) System.out.println(Thread.currentThread().getName() + ": open new PK lookup reader=" + lookupReader);
                    lookup = new PerThreadVersionPKLookup(lookupReader, "id");
                  }

                  Long truthVersion = truth.get(id);
                  if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   truthVersion=" + truthVersion);

                  boolean doIndex;
                  if (currentVersion == missingValue) {
                    if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   id not in RT cache");
                    int otherDocID = lookup.lookup(new BytesRef(id), newVersion+1);
                    if (otherDocID == -1) {
                      if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   id not in index, or version is <= newVersion; will index");
                      doIndex = true;
                    } else {
                      if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   id is in index with version=" + lookup.getVersion() + "; will not index");
                      doIndex = false;
                      if (truthVersion.longValue() !=lookup.getVersion()) {
                        System.out.println(Thread.currentThread() + ": now fail0!");
                      }
                      assertEquals(truthVersion.longValue(), lookup.getVersion());
                    }
                  } else {
                    if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   id is in RT cache: currentVersion=" + currentVersion);
                    doIndex = newVersion > currentVersion;
                  }

                  if (doIndex) {
                    if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   now index");
                    boolean passes = truthVersion == null || truthVersion.longValue() <= newVersion;
                    if (passes == false) {
                      System.out.println(Thread.currentThread() + ": now fail!");
                    }
                    assertTrue(passes);
                    Document doc = new Document();
                    doc.add(makeIDField(id, newVersion));
                    w.updateDocument(new Term("id", id), doc);
                    truth.put(id, newVersion);
                    versionValues.add(id, newVersion);
                  } else {
                    if (VERBOSE) System.out.println(Thread.currentThread().getName() + ":   skip index");
                    assertNotNull(truthVersion);
                    assertTrue(truthVersion.longValue() >= newVersion);
                  }
                } finally {
                  mgr.release(s);
                }
              }
            }
          }
        };
      threads[i].start();
    }

    startingGun.countDown();

    // Keep reopening the NRT reader until all indexing threads are done:
    refreshLoop:
    while (true) {
      Thread.sleep(TestUtil.nextInt(random(), 1, 10));
      mgr.maybeRefresh();
      for (Thread thread : threads) {
        if (thread.isAlive()) {
          continue refreshLoop;
        }
      }

      break;
    }

    // Verify final index against truth:
    for(int i=0;i<2;i++) {
      mgr.maybeRefresh();
      IndexSearcher s = mgr.acquire();
      try {
        IndexReader r = s.getIndexReader();
        // cannot assert this: maybe not all IDs were indexed
        /*
        assertEquals(numIDs, r.numDocs());
        if (i == 1) {
          // After forceMerge no deleted docs:
          assertEquals(numIDs, r.maxDoc());
        }
        */
        PerThreadVersionPKLookup lookup = new PerThreadVersionPKLookup(r, "id");
        for(Map.Entry<String,Long> ent : truth.entrySet()) {
          assertTrue(lookup.lookup(new BytesRef(ent.getKey()), -1L) != -1);
          assertEquals(ent.getValue().longValue(), lookup.getVersion());
        }
      } finally {
        mgr.release(s);
      }

      if (i == 1) {
        break;
      }

      // forceMerge and verify again
      w.forceMerge(1);
    }

    mgr.close();
    w.close();
    dir.close();
  }
View Full Code Here

    super.init();
  }

  @Test
  public void defaultSearch() throws IOException {
    SearcherManager searcherManager = crescentSearcherManager.getSearcherManager("sample");
    IndexSearcher indexSearcher = searcherManager.acquire();
   
    Term t = new Term("title", "2");
    Query q = new TermQuery(t);
   
    TopDocs topDocs = indexSearcher.search(q, 5);
View Full Code Here

    //IndexWriterManager indexWriterManager = IndexWriterManager.getIndexWriterManager();
    //IndexWriter indexWriter = indexWriterManager.getIndexWriter("sample");
    //IndexReader indexReader = IndexReader.open(indexWriter, true);
   
    SearcherManager searcherManager = crescentSearcherManager.getSearcherManager("sample");
    IndexSearcher indexSearcher = searcherManager.acquire();
   
    IndexReader indexReader = indexSearcher.getIndexReader();
   
    TopDocs topDocs = indexSearcher.search(new TermQuery(new Term("dscr", "입니다")), 3);
   
View Full Code Here

  }
 
  @Test
  public void getSearcher() throws IOException {
    IndexSearcher indexSearcher = null;
    SearcherManager searcherManager = crescentSearcherManager.getSearcherManager("sample");
   
    indexSearcher = searcherManager.acquire();
   
    Assert.assertNotNull(indexSearcher);
  }
View Full Code Here

TOP

Related Classes of org.apache.lucene.search.SearcherManager

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.