Lucene 4.0在文本搜索中

时间:2013-01-17 09:18:32

标签: java lucene

我正在使用lucene 4.0和java。我正在尝试在字符串中搜索字符串。如果我们看看lucene hello world示例,我希望在短语“inLuceneAction”中找到文本“lucene”。我想让它在这种情况下找到我两个匹配而不是一个。

关于如何做的任何想法?

由于

public class HelloLucene {
 public static void main(String[] args) throws IOException, ParseException {
// 0. Specify the analyzer for tokenizing text.
//    The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);

// 1. create the index
Directory index = new RAMDirectory();

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);

IndexWriter w = new IndexWriter(index, config);
addDoc(w, "inLuceneAction", "193398817");
addDoc(w, "Lucene for Dummies", "55320055Z");
addDoc(w, "Managing Gigabytes", "55063554A");
addDoc(w, "The Art of Computer Science", "9900333X");
w.close();

// 2. query
String querystr = args.length > 0 ? args[0] : "lucene";

// the "title" arg specifies the default field to use
// when no field is explicitly specified in the query.
Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);

// 3. search
int hitsPerPage = 10;
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

// 4. display results
System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
  int docId = hits[i].doc;
  Document d = searcher.doc(docId);
  System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
}
// reader can only be closed when there
// is no need to access the documents any more.
reader.close(); 
}
private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
Document doc = new Document();
doc.add(new TextField("title", title, Field.Store.YES));

// use a string field for isbn because we don't want it tokenized
doc.add(new StringField("isbn", isbn, Field.Store.YES));
w.addDocument(doc);
}
}

1 个答案:

答案 0 :(得分:1)

如果您使用默认方式为术语编制索引,意味着inLuceneAction是一个术语,Lucene将无法seek给定Lucene这个术语,因为它有不同的前缀。分析此字符串,以便生成三个索引字词:in Lucene Action,然后您将获取它。你要么找到一个现成的分析仪,要么你必须自己编写。编写自己的分析器有点超出单个StackOverflow答案的范围,但是一个很好的起点是org.apache.lucene.analysis软件包Javadoc页面底部的软件包信息。