簡體   English   中英

文本搜索中的Lucene 4.0

[英]Lucene 4.0 in text search

我在Java中使用Lucene 4.0。 我正在嘗試在字符串中搜索字符串。 如果我們看一下lucene hello世界示例,我希望在短語“ 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);
}
}

如果您以默認方式為這些術語建立索引,這意味着在inLuceneAction是一個術語,由於Lucene具有不同的前綴,因此Lucene將無法seek該術語。 分析此字符串,以使其產生三個索引術語: in Lucene Action ,然后將其提取。 您將為此找到現成的分析儀,或者必須自己編寫。 編寫自己的分析器對於單個StackOverflow答案來說有點超出范圍,但是一個很好的起點是org.apache.lucene.analysis包Javadoc頁面底部的包信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM