Package org.apache.lucene.search

Examples of org.apache.lucene.search.Searcher


        RAMDirectory dir = new RAMDirectory();
        IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.LIMITED);
        writer.addDocument(makeDocumentWithFields());
        writer.close();

        Searcher searcher = new IndexSearcher(dir, true);

  // search for something that does exists
  Query query = new TermQuery(new Term("keyword", "test1"));

  // ensure that queries return expected results without DateFilter first
        ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
  assertEquals(1, hits.length);

         doAssert(searcher.doc(hits[0].doc), true);
         searcher.close();
    }
View Full Code Here


      writer.addDocument(doc);
      field.setValue("id3");
      writer.addDocument(doc);
      writer.close();

      Searcher searcher = new IndexSearcher(dir, true);

      Query query = new TermQuery(new Term("keyword", "test"));

      // ensure that queries return expected results without DateFilter first
      ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
      assertEquals(3, hits.length);
      int result = 0;
      for(int i=0;i<3;i++) {
        Document doc2 = searcher.doc(hits[i].doc);
        Field f = doc2.getField("id");
        if (f.stringValue().equals("id1"))
          result |= 1;
        else if (f.stringValue().equals("id2"))
          result |= 2;
        else if (f.stringValue().equals("id3"))
          result |= 4;
        else
          fail("unexpected id field");
      }
      searcher.close();
      dir.close();
      assertEquals("did not see all IDs", 7, result);
    }
View Full Code Here

      create = true;
    }

    FSDirectory dir = FSDirectory.open(indexDir);
    try {
      Searcher searcher = null;
      boolean checkLastModified = false;
      if (!create) {
        try {
          searcher = new IndexSearcher(dir, true);
          checkLastModified = true;
        } catch (IOException ioe) {
          log("IOException: " + ioe.getMessage());
          // Empty - ignore, which indicates to index all
          // documents
        }
      }

      log("checkLastModified = " + checkLastModified, Project.MSG_VERBOSE);

      IndexWriter writer =
        new IndexWriter(dir, analyzer, create, IndexWriter.MaxFieldLength.LIMITED);

      writer.setUseCompoundFile(useCompoundIndex);
      int totalFiles = 0;
      int totalIndexed = 0;
      int totalIgnored = 0;
      try {
        writer.setMergeFactor(mergeFactor);

        for (int i = 0; i < rcs.size(); i++) {
          ResourceCollection rc = rcs.elementAt(i);
          if (rc.isFilesystemOnly()) {
            Iterator resources = rc.iterator();
            while (resources.hasNext()) {
              Resource r = (Resource) resources.next();
              if (!r.isExists() || !(r instanceof FileResource)) {
                continue;
              }
             
              totalFiles++;

              File file = ((FileResource) r).getFile();
             
              if (!file.exists() || !file.canRead()) {
                throw new BuildException("File \"" +
                                         file.getAbsolutePath()
                                         + "\" does not exist or is not readable.");
              }

              boolean indexIt = true;

              if (checkLastModified) {
                Term pathTerm =
                  new Term("path", file.getPath());
                TermQuery query =
                  new TermQuery(pathTerm);
                ScoreDoc[] hits = searcher.search(query, null, 1).scoreDocs;

                // if document is found, compare the
                // indexed last modified time with the
                // current file
                // - don't index if up to date
                if (hits.length > 0) {
                  Document doc = searcher.doc(hits[0].doc);
                  String indexModified =
                    doc.get("modified").trim();
                  if (indexModified != null) {
                    long lastModified = 0;
                    try {
                      lastModified = DateTools.stringToTime(indexModified);
                    } catch (ParseException e) {
                      // if modified time is not parsable, skip
                    }
                    if (lastModified == file.lastModified()) {
                      // TODO: remove existing document
                      indexIt = false;
                    }
                  }
                }
              }

              if (indexIt) {
                try {
                  log("Indexing " + file.getPath(),
                      Project.MSG_VERBOSE);
                  Document doc =
                    handler.getDocument(file);

                  if (doc == null) {
                    totalIgnored++;
                  } else {
                    // Add the path of the file as a field named "path".  Use a Keyword field, so
                    // that the index stores the path, and so that the path is searchable
                    doc.add(new Field("path", file.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));

                    // Add the last modified date of the file a field named "modified".  Use a
                    // Keyword field, so that it's searchable, but so that no attempt is made
                    // to tokenize the field into words.
                    doc.add(new Field("modified", DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND), Field.Store.YES, Field.Index.NOT_ANALYZED));

                    writer.addDocument(doc);
                    totalIndexed++;
                  }
                } catch (DocumentHandlerException e) {
                  throw new BuildException(e);
                }
              }
            }
            // for j
          }
          // if (fs != null)
        }
        // for i

        writer.optimize();
      }
        //try
      finally {
        // always make sure everything gets closed,
        // no matter how we exit.
        writer.close();
        if (searcher != null) {
          searcher.close();
        }
      }

      Date end = new Date();
View Full Code Here

                          Field.Store.NO, Field.Index.ANALYZED));
      writer.addDocument(doc);
    }
    writer.optimize();
    writer.close();
    Searcher searcher = new IndexSearcher(indexStore, true);

    Sort sort = new Sort();
    Query queryX = new TermQuery(new Term ("contents", "x"));
    Query queryY = new TermQuery(new Term ("contents", "y"));
   
View Full Code Here

    _TestUtil.checkIndex(dir);

    /*
     * Verify the index
     */        
    Searcher searcher = new IndexSearcher(dir, true);
    searcher.setSimilarity(new SimpleSimilarity());
       
    Term a = new Term("noTf", term);
    Term b = new Term("tf", term);
    Term c = new Term("noTf", "notf");
    Term d = new Term("tf", "tf");
    TermQuery q1 = new TermQuery(a);
    TermQuery q2 = new TermQuery(b);
    TermQuery q3 = new TermQuery(c);
    TermQuery q4 = new TermQuery(d);

       
    searcher.search(q1,
                    new CountingHitCollector() {
                      private Scorer scorer;
                      @Override
                      public final void setScorer(Scorer scorer) {
                        this.scorer = scorer;
                      }
                      @Override
                      public final void collect(int doc) throws IOException {
                        //System.out.println("Q1: Doc=" + doc + " score=" + score);
                        float score = scorer.score();
                        assertTrue(score==1.0f);
                        super.collect(doc);
                      }
                    });
    //System.out.println(CountingHitCollector.getCount());
       
       
    searcher.search(q2,
                    new CountingHitCollector() {
                      private Scorer scorer;
                      @Override
                      public final void setScorer(Scorer scorer) {
                        this.scorer = scorer;
                      }
                      @Override
                      public final void collect(int doc) throws IOException {
                        //System.out.println("Q2: Doc=" + doc + " score=" + score);
                        float score = scorer.score();
                        assertTrue(score==1.0f+doc);
                        super.collect(doc);
                      }
                    });
    //System.out.println(CountingHitCollector.getCount());
        
       
       
       
       
    searcher.search(q3,
                    new CountingHitCollector() {
                      private Scorer scorer;
                      @Override
                      public final void setScorer(Scorer scorer) {
                        this.scorer = scorer;
                      }
                      @Override
                      public final void collect(int doc) throws IOException {
                        //System.out.println("Q1: Doc=" + doc + " score=" + score);
                        float score = scorer.score();
                        assertTrue(score==1.0f);
                        assertFalse(doc%2==0);
                        super.collect(doc);
                      }
                    });
    //System.out.println(CountingHitCollector.getCount());
       
       
    searcher.search(q4,
                    new CountingHitCollector() {
                      private Scorer scorer;
                      @Override
                      public final void setScorer(Scorer scorer) {
                        this.scorer = scorer;
                      }
                      @Override
                      public final void collect(int doc) throws IOException {
                        float score = scorer.score();
                        //System.out.println("Q1: Doc=" + doc + " score=" + score);
                        assertTrue(score==1.0f);
                        assertTrue(doc%2==0);
                        super.collect(doc);
                      }
                    });
    //System.out.println(CountingHitCollector.getCount());
       
       
       
    BooleanQuery bq = new BooleanQuery();
    bq.add(q1,Occur.MUST);
    bq.add(q4,Occur.MUST);
       
    searcher.search(bq,
                    new CountingHitCollector() {
                      @Override
                      public final void collect(int doc) throws IOException {
                        //System.out.println("BQ: Doc=" + doc + " score=" + score);
                        super.collect(doc);
                      }
                    });
    assertTrue(15 == CountingHitCollector.getCount());
       
    searcher.close();    
    dir.close();
  }
View Full Code Here

    Analyzer analyzer = new WhitespaceAnalyzer();
 
    IndexWriter writer = new IndexWriter(dir, analyzer, true, MaxFieldLength.LIMITED);
    writer.close();
 
    Searcher searcher = new IndexSearcher(dir, true);
 
    Query query = new TermQuery(new Term("none", "none"));
 
    QueryWrapperFilter queryFilter = new QueryWrapperFilter(query);
    CachingWrapperFilter cachingFilter = new CachingWrapperFilter(queryFilter);
 
    searcher.search(query, cachingFilter, 1);
 
    CachingWrapperFilter cachingFilter2 = new CachingWrapperFilter(queryFilter);
    Filter[] chain = new Filter[2];
    chain[0] = cachingFilter;
    chain[1] = cachingFilter2;
    ChainedFilter cf = new ChainedFilter(chain);
 
    // throws java.lang.ClassCastException: org.apache.lucene.util.OpenBitSet cannot be cast to java.util.BitSet
    searcher.search(new MatchAllDocsQuery(), cf, 1);
  }
View Full Code Here

    // Remove the resource holder from the thread.
    ResourceBindingManager.unbindResource(this.searcherFactory);

    // Close searcher.
    Searcher searcher = holder.getSearcher();
    if (logger.isDebugEnabled()) {
      logger.debug("Closing Lucene searcher [" + searcher + "]");
    }
    SearcherFactoryUtils.releaseSearcher(this.searcherFactory,searcher);
  }
View Full Code Here

   * @param filter the query filter
   * @param sort the query sorter
   * @return the search results
   */
  private List doSearch(Query query,HitExtractor extractor,Filter filter,Sort sort) {
    Searcher searcher=SearcherFactoryUtils.getSearcher(getSearcherFactory());
    try {
      Hits hits=null;
      if( filter!=null && sort!=null ) {
        hits=searcher.search(query,filter,sort);
      } else if( filter!=null ) {
        hits=searcher.search(query,filter);
      } else if( sort!=null ) {
        hits=searcher.search(query,sort);
      } else {
        hits=searcher.search(query);
      }
      return extractHits(hits,extractor);
    } catch (IOException ex) {
      throw new LuceneSearchException("Error during the search",ex);
    } finally {
View Full Code Here

   * @param results the Lucene hit collector
   * @see QueryCreator#createQuery(Analyzer)
   * @see org.apache.lucene.search.HitCollector
   */
  public void search(QueryCreator queryCreator,HitCollector results) {
    Searcher searcher=SearcherFactoryUtils.getSearcher(getSearcherFactory());
    try {
      searcher.search(queryCreator.createQuery(getAnalyzer()),results);
    } catch (IOException ex) {
      throw new LuceneSearchException("Error during the search",ex);
    } catch (ParseException ex) {
      throw new LuceneSearchException("Error during the parse of the query",ex);
    } finally {
View Full Code Here

   * created.
   * @param callback the callback object that exposes the Searcher
   * @see SearcherCallback#doWithSearcher(Searcher)
   */
  public Object search(SearcherCallback callback) {
    Searcher searcher=SearcherFactoryUtils.getSearcher(getSearcherFactory());
    try {
      return callback.doWithSearcher(searcher);
    } catch (IOException ex) {
      throw new LuceneSearchException("Error during searching",ex);
    } catch (ParseException ex) {
View Full Code Here

TOP

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

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.