Monday, March 16, 2015

Querying the Lucene Index

Note: Imports removed for legibility.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.ibm.ted.ebear.lucene;

public final class QueryDemo1 {

 public static LogManager logger = new LogManager(QueryDemo1.class);

 private static BooleanQuery createBooleanQuery(Analyzer analyzer) throws ParseException {
  BooleanQuery booleanQuery = new BooleanQuery();

  Query query1 = new QueryParser("content", analyzer).parse(String.format("(%s) AND (%s)", "alpha", "beta"));
  query1.setBoost(0.9f);
  booleanQuery.add(query1, Occur.SHOULD);

  Query query2 = new QueryParser("title", analyzer).parse(String.format("(%s) AND (%s)", "alpha", "beta"));
  query2.setBoost(1.1f);
  booleanQuery.add(query2, Occur.SHOULD);

  return booleanQuery;
 }

 public static void main(String... args) throws Throwable {

  Directory directory = FSDirectory.open(new File("/home/astoruser/lucene/01/"));
  IndexReader reader = DirectoryReader.open(directory);

  Analyzer analyzer = new StandardAnalyzer();
  IndexSearcher searcher = new IndexSearcher(reader);

  TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
  BooleanQuery booleanQuery = createBooleanQuery(analyzer);
  searcher.search(booleanQuery, collector);

  ScoreDoc[] hits = collector.topDocs().scoreDocs;
  for (ScoreDoc hit : hits) {

   Document doc = searcher.doc(hit.doc);
   logger.debug("Result (score = %s, filename = %s)", hit.score, doc.get("filename"));
  }
 }
}

No comments:

Post a Comment