2017-01-03 164 views
1

我正在使用Apache Lucene 5.5.3。我在我的代碼中使用org.apache.lucene.analysis.standard.StandardAnalyzer並使用下面的代碼片段來創建索引。Apache Lucene 5.5.3 - 搜索以特殊字符結尾的字符串

Document doc = new Document(); 

doc.add(new TextField("userName", getUserName(), Field.Store.YES)); 

現在,如果我搜索字符串「ALL-」,那麼我沒有收到任何搜索結果,但如果我搜索字符串「ALL-分類」,然後我得到了一些搜索結果。

對於帶有特殊字符'+','。','!'的字符串也是如此。等

下面是我的搜索代碼: -

Directory directory = new RAMDirectory(); 
IndexReader reader = DirectoryReader.open(directory); 
IndexSearcher searcher = new IndexSearcher(reader); 
Document document = new Document(); 
document.add(new TextField("body", ALL-THE GLITTERS IS NOT GOLD, Field.Store.YES)); 

IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(buildAnalyzer())); 
writer.addDocument(document); 
writer.commit(); 

Builder builder = new BooleanQuery.Builder(); 

Query query1 = new QueryParser(IndexAttribute.USER_NAME, buildAnalyzer()).parse(searchQUery+"*"); 
Query query2 = new QueryParser(IndexAttribute.IS_VETERAN, buildAnalyzer()).parse(""+isVeteran); 
builder.add(query1, BooleanClause.Occur.MUST); 
builder.add(query2, BooleanClause.Occur.MUST); 

Query q = builder.build(); 

TopDocs docs = searcher.search(q, 10); 
ScoreDoc[] hits = docs.scoreDocs; 

private static Analyzer buildAnalyzer() throws IOException { 
    return CustomAnalyzer.builder().withTokenizer("whitespace").addTokenFilter("lowercase") 
      .addTokenFilter("standard").build(); 
} 

所以,請建議我在此。

+0

因此,您最後在您的字符串中進行了詳細說明?什麼是索引值?也顯示您的搜索代碼。 –

+0

是的,我最後有一個特殊的字符。我編入索引的值是'ALL-THE GLITTERS IS NOT GOLD'。 – Raj

+0

您需要爲'q.toString()'顯示不成功的搜索結果的值,並指定變量的值 - 'searchQUery'&'isVeteran'。 –

回答

0

我得到了WildcardQuery,StringField和MultiFieldQueryParser組合的解決方案。除了這些類之外,我們還要做的就是跳過查詢字符串中的空格。

0

請參考第Escaping Special Characters知道Lucene 5.5.3中的特殊字符。

正如上述文章中建議,您需要將一個\或者您可以使用QueryParser類的方法public static String escape(String s)來實現相同的。

+0

謝謝Sabir的回覆。我試過了,但沒有按預期工作。我用WildcardQuery,StringField和MultiFieldQueryParser組合獲得瞭解決方案。除了這些類之外,我們還要做的是轉義查詢字符串中的空格。 – Raj

相關問題