我在Android上使用Lucene 3.6.2。使用的代碼和觀察結果如下。Lucene搜索兩個或更多單詞不能在Android上工作
索引代碼:
public void indexBookContent(Book book, File externalFilesDir) throws Exception {
IndexWriter indexWriter = null;
NIOFSDirectory directory = null;
directory = new NIOFSDirectory(new File(externalFilesDir.getPath() + "/IndexFile", book.getBookId()));
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_36, new StandardAnalyzer(LUCENE_36));
indexWriter = new IndexWriter(directory, indexWriterConfig);
Document document = createFieldsForContent();
String pageContent = Html.fromHtml(decryptedPage).toString();
((Field) document.getFieldable("content")).setValue(pageContent);
((Field) document.getFieldable("content")).setValue(pageContent);
((Field) document.getFieldable("content")).setValue(pageContent.toLowerCase());
}
private Document createFieldsForContent() {
Document document = new Document();
Field contentFieldLower = new Field("content", "", YES, NOT_ANALYZED);
document.add(contentFieldLower);
Field contentField = new Field("content", "", YES, ANALYZED);
document.add(contentField);
Field contentFieldNotAnalysed = new Field("content", "", YES, NOT_ANALYZED);
document.add(contentFieldNotAnalysed);
Field recordIdField = new Field("recordId", "", YES, ANALYZED);
document.add(recordIdField);
return document;
}
public JSONArray searchBook(String bookId, String searchText, File externalFieldsDir, String filter) throws Exception {
List<SearchResultData> searchResults = null;
NIOFSDirectory directory = null;
IndexReader indexReader = null;
IndexSearcher indexSearcher = null;
directory = new NIOFSDirectory(new File(externalFieldsDir.getPath() + "/IndexFile", bookId));
indexReader = IndexReader.open(directory);
indexSearcher = new IndexSearcher(indexReader);
Query finalQuery = constructSearchQuery(searchText, filter);
TopScoreDocCollector collector = TopScoreDocCollector.create(100, false);
indexSearcher.search(finalQuery, collector);
ScoreDoc[] scoreDocs = collector.topDocs().scoreDocs;
}
private Query constructSearchQuery(String searchText, String filter) throws ParseException {
QueryParser contentQueryParser = new QueryParser(LUCENE_36, "content", new StandardAnalyzer(LUCENE_36));
contentQueryParser.setAllowLeadingWildcard(true);
contentQueryParser.setLowercaseExpandedTerms(false);
String wildCardSearchText = "*" + QueryParser.escape(searchText) + "*";
// Query Parser used.
Query contentQuery = contentQueryParser.parse(wildCardSearchText);
return contentQueryParser.parse(wildCardSearchText);
}
我已經經歷了這樣: 「Lucene: Multi-word phrases as search terms」,和我的邏輯似乎並沒有不同。
我的疑問是字段被覆蓋。 另外,我需要中文語言支持,它與這個代碼一起工作,除了兩個或更多字支持的問題。
我似乎不明白你確切的問題是什麼。就像在你提到的那個鏈接中,當你輸入多個單詞時不會返回正確的結果。在哪個字段中搜索以及通過哪個查詢,舉例 – Eypros
讓我在這裏陳述我的觀察結果。單個單詞的搜索工作正常,單箇中文單詞和特殊字符也是如此。但是如果我搜索兩個詞,我沒有得到任何結果。我將更新上面的代碼來指定查詢詳細信息 – Zooter