Example usage for org.apache.lucene.search IndexSearcher IndexSearcher

List of usage examples for org.apache.lucene.search IndexSearcher IndexSearcher

Introduction

In this page you can find the example usage for org.apache.lucene.search IndexSearcher IndexSearcher.

Prototype

public IndexSearcher(IndexReaderContext context) 

Source Link

Document

Creates a searcher searching the provided top-level IndexReaderContext .

Usage

From source file:com.leavesfly.lia.searching.QueryParserTest.java

License:Apache License

protected void setUp() throws Exception {
    analyzer = new WhitespaceAnalyzer();
    dir = TestUtil.getBookIndexDirectory();
    searcher = new IndexSearcher(dir);
}

From source file:com.leavesfly.lia.searching.ScoreTest.java

License:Apache License

public void testSimple() throws Exception {
    indexSingleFieldDocs(new Field[] { new Field("contents", "x", Field.Store.YES, Field.Index.ANALYZED) });
    IndexSearcher searcher = new IndexSearcher(directory);
    searcher.setSimilarity(new SimpleSimilarity());

    Query query = new TermQuery(new Term("contents", "x"));
    Explanation explanation = searcher.explain(query, 0);
    System.out.println(explanation);

    TopDocs matches = searcher.search(query, 10);
    assertEquals(1, matches.totalHits);/* w  w  w . j  a  va2 s .  c o m*/

    assertEquals(1F, matches.scoreDocs[0].score, 0.0);

    searcher.close();
}

From source file:com.leavesfly.lia.searching.TermRangeQueryTest.java

License:Apache License

public void testTermRangeQuery() throws Exception {
    Directory dir = TestUtil.getBookIndexDirectory();
    IndexSearcher searcher = new IndexSearcher(dir);
    TermRangeQuery query = new TermRangeQuery("title2", "d", "j", true, true);

    TopDocs matches = searcher.search(query, 100);
    /*// w ww  .j  av  a  2s  .c o m
     * for(int i=0;i<matches.totalHits;i++) { System.out.println("match " +
     * i + ": " + searcher.doc(matches.scoreDocs[i].doc).get("title2")); }
     */
    assertEquals(3, matches.totalHits);
    searcher.close();
    dir.close();
}

From source file:com.leavesfly.lia.tool.BooksMoreLikeThis.java

License:Apache License

public static void main(String[] args) throws Throwable {

    String indexDir = System.getProperty("index.dir");
    FSDirectory directory = FSDirectory.open(new File(indexDir));
    IndexReader reader = IndexReader.open(directory);

    IndexSearcher searcher = new IndexSearcher(reader);

    int numDocs = reader.maxDoc();

    MoreLikeThis mlt = new MoreLikeThis(reader); // #A
    mlt.setFieldNames(new String[] { "title", "author" });
    mlt.setMinTermFreq(1); // #B
    mlt.setMinDocFreq(1);//from w w  w.  ja  v a2s . c om

    for (int docID = 0; docID < numDocs; docID++) { // #C
        System.out.println();
        Document doc = reader.document(docID);
        System.out.println(doc.get("title"));

        Query query = mlt.like(docID); // #D
        System.out.println("  query=" + query);

        TopDocs similarDocs = searcher.search(query, 10);
        if (similarDocs.totalHits == 0)
            System.out.println("  None like this");
        for (int i = 0; i < similarDocs.scoreDocs.length; i++) {
            if (similarDocs.scoreDocs[i].doc != docID) { // #E
                doc = reader.document(similarDocs.scoreDocs[i].doc);
                System.out.println("  -> " + doc.getField("title").stringValue());
            }
        }
    }

    searcher.close();
    reader.close();
    directory.close();
}

From source file:com.leavesfly.lia.tool.ChainedFilterTest.java

License:Apache License

public void setUp() throws Exception {
    directory = new RAMDirectory();
    IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(),
            IndexWriter.MaxFieldLength.UNLIMITED);

    Calendar cal = Calendar.getInstance();
    cal.set(2009, 1, 1, 0, 0); // A

    for (int i = 0; i < MAX; i++) {
        Document doc = new Document();
        doc.add(new Field("key", "" + (i + 1), Field.Store.YES, Field.Index.NOT_ANALYZED));
        doc.add(new Field("owner", (i < MAX / 2) ? "bob" : "sue", Field.Store.YES, Field.Index.NOT_ANALYZED));
        doc.add(new Field("date", DateTools.timeToString(cal.getTimeInMillis(), DateTools.Resolution.DAY),
                Field.Store.YES, Field.Index.NOT_ANALYZED));
        writer.addDocument(doc);//from w ww.  j  a v a  2s  .  co m

        cal.add(Calendar.DATE, 1);
    }

    writer.close();

    searcher = new IndexSearcher(directory);

    BooleanQuery bq = new BooleanQuery(); // B
    bq.add(new TermQuery(new Term("owner", "bob")), // B
            BooleanClause.Occur.SHOULD); // B
    bq.add(new TermQuery(new Term("owner", "sue")), // B
            BooleanClause.Occur.SHOULD); // B
    query = bq;

    cal.set(2099, 1, 1, 0, 0);
    dateFilter = TermRangeFilter.Less("date", // C
            DateTools.timeToString( // C
                    cal.getTimeInMillis(), // C
                    DateTools.Resolution.DAY));// C

    bobFilter = new CachingWrapperFilter( // D
            new QueryWrapperFilter( // D
                    new TermQuery(new Term("owner", "bob")))); // D

    sueFilter = new CachingWrapperFilter( // E
            new QueryWrapperFilter( // E
                    new TermQuery(new Term("owner", "sue")))); // E
}

From source file:com.leavesfly.lia.tool.HighlightTest.java

License:Apache License

public void testHits() throws Exception {
    IndexSearcher searcher = new IndexSearcher(TestUtil.getBookIndexDirectory());
    TermQuery query = new TermQuery(new Term("title", "action"));
    TopDocs hits = searcher.search(query, 10);

    QueryScorer scorer = new QueryScorer(query, "title");
    Highlighter highlighter = new Highlighter(scorer);
    highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));

    Analyzer analyzer = new SimpleAnalyzer();

    for (ScoreDoc sd : hits.scoreDocs) {
        Document doc = searcher.doc(sd.doc);
        String title = doc.get("title");

        TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), sd.doc, "title", doc,
                analyzer);// www  .  ja  v a 2 s. c o m
        String fragment = highlighter.getBestFragment(stream, title);

        System.out.println(fragment);
    }
}

From source file:com.leavesfly.lia.tool.SpatialLuceneExample.java

License:Apache License

public void findNear(String what, double latitude, double longitude, double radius)
        throws CorruptIndexException, IOException {
    IndexSearcher searcher = new IndexSearcher(directory);

    DistanceQueryBuilder dq;// w  ww . j  a  v  a2 s .  c  o  m
    dq = new DistanceQueryBuilder(latitude, // #A
            longitude, // #A
            radius, // #A
            latField, // #A
            lngField, // #A
            tierPrefix, // #A
            true); // #A

    Query tq;
    if (what == null)
        tq = new TermQuery(new Term("metafile", "doc")); // #B
    else
        tq = new TermQuery(new Term("name", what));

    DistanceFieldComparatorSource dsort; // #C
    dsort = new DistanceFieldComparatorSource( // #C
            dq.getDistanceFilter()); // #C
    Sort sort = new Sort(new SortField("foo", dsort)); // #C

    TopDocs hits = searcher.search(tq, dq.getFilter(), 10, sort);

    Map<Integer, Double> distances = // #D
            dq.getDistanceFilter().getDistances(); // #D

    System.out.println("Number of results: " + hits.totalHits);
    System.out.println("Found:");
    for (ScoreDoc sd : hits.scoreDocs) {
        int docID = sd.doc;
        Document d = searcher.doc(docID);

        String name = d.get("name");
        double rsLat = NumericUtils.prefixCodedToDouble(d.get(latField));
        double rsLng = NumericUtils.prefixCodedToDouble(d.get(lngField));
        Double geo_distance = distances.get(docID);

        System.out.printf(name + ": %.2f Miles\n", geo_distance);
        System.out.println("\t\t(" + rsLat + "," + rsLng + ")");
    }
}

From source file:com.liang.minisearch.domain.search.Engine.java

public List<QueryDocument> search(String queryString) throws ParseException, IOException {
    List<QueryDocument> results = new ArrayList<>();

    IndexSearcher searcher = new IndexSearcher(this.getReader());

    // Parse user input query
    Query query = new QueryParser(FIELD_CONTENT, new StandardAnalyzer()).parse(queryString);

    // Get top n matching documents
    TopDocs topDocs = searcher.search(query, NUM_TOP_RESULT);
    ScoreDoc[] hits = topDocs.scoreDocs;
    for (ScoreDoc hit : hits) {
        Document doc = searcher.doc(hit.doc);
        QueryDocument result = new QueryDocument();
        result.setUrl(doc.get(FIELD_URL));
        result.setScore(hit.score);//w w w .j  av a  2 s  .c  om

        results.add(result);
    }

    return results;
}

From source file:com.liferay.portal.search.lucene.dump.DumpIndexDeletionPolicyTest.java

License:Open Source License

private void _assertHits(Directory directory, String fieldName, String fieldValue, int totalHits)
        throws Exception {

    IndexSearcher indexSearcher = new IndexSearcher(directory);

    Term term = new Term(fieldName, fieldValue);

    TermQuery termQuery = new TermQuery(term);

    TopDocs topDocs = indexSearcher.search(termQuery, 1);

    assertEquals(totalHits, topDocs.totalHits);
}

From source file:com.liferay.portal.search.lucene.dump.IndexAccessorImplTest.java

License:Open Source License

private void _assertHits(String key, boolean expectHit) throws Exception {
    IndexSearcher indexSearcher = new IndexSearcher(_indexAccessorImpl.getLuceneDir());

    for (int i = 0; i < _documentsCount * 2; i++) {
        Term term = new Term("name", key + i);

        TermQuery termQuery = new TermQuery(term);

        TopDocs topDocs = indexSearcher.search(termQuery, 1);

        if (i < _documentsCount) {
            if (expectHit) {
                assertEquals(1, topDocs.totalHits);
            } else {
                assertEquals(0, topDocs.totalHits);
            }/*from w  w  w .ja  v  a 2 s  . c  o m*/
        } else {
            assertEquals(0, topDocs.totalHits);
        }
    }

    indexSearcher.close();
}