0

我在 java 中使用 lucene 4.0。我正在尝试在字符串中搜索字符串。如果我们查看 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);
}
}
4

1 回答 1

1

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

于 2013-01-17T09:47:30.207 回答