我正在構建一個項目,可以生成用於搜索lucene索引的自定義查詢。我做了一些研究,發現了許多方法來查詢Lucene索引,如:自定義代碼來結合所有類型的lucene查詢類型
- 布爾搜索:現場:白布和現場鞋
- 項查詢搜索:現場:我是一個男孩
- 鄰近查詢搜索:5/5/2016-10/6/2017
什麼是困惑的是:可以QueryParser做所有這些查詢,或者你必須編寫一個方法來做個別查詢,如在Tutorialspoint查詢編程,其中他們給出了每種查詢的例子以及如何實現它。
這是到目前爲止我的代碼:
/** Setting the searcher method to search the index passed **/
private void indexSearch(String indexDir, String queryX, int repeat, int hitsPerPage, String field, boolean raw) throws Exception{
/*** starting the method process ***/
// Here we process the searcher data
reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexDir)));
searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer();
// BufferedReader
BufferedReader in = null;
boolean checkQ=false;
// Lets check if query is a file
File cfile=new File(queryX);
// Now lets check
if(cfile.isFile()){
// We process queryX as a file
in = Files.newBufferedReader(Paths.get(queryX), StandardCharsets.UTF_8);
checkQ=true;
}
else{
checkQ=false;
}
/** We pass query in different query types **/
parser = new QueryParser(field, analyzer);
// Here we are going to select the data we use for line
String line = checkQ != true ? queryX : in.readLine();
// Now lets trim the line
line = line.trim();
/******* NOW LETS CALL FUNCTION TO PASS QUERY ******/
search(line);
}
/** Making complex query priviledge to get data **/
public TopDocs search(String searchQuery) throws Exception{
// Lets pass query
query = parser.parse(searchQuery);
// Now lets return
return searcher.search(query, 100);
}
public TopDocs search(Query query) throws IOException{
return searcher.search(query, 100);
}
/**** Making the getDocument for the search ****/
public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException{
return searcher.doc(scoreDoc.doc);
}
/** Simple command-line based search demo. */
public void close() throws Exception {
// Lets close reader
reader.close();
}
這裏是使用不同的查詢類型的教程點例如:
private void searchUsingTermQuery(String searchQuery)throws IOException, ParseException{
searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name
Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
//create the term query object
Query query = new TermQuery(term);
//do the search
TopDocs hits = searcher.search(query);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms");
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
我希望能夠給所有的Lucene的查詢類型組合所以我可以查詢我的索引,如本教程中所述:http://www.javaranch.com/journal/2004/04/Lucene.html
我的項目從xml文件創建動態字段並使用它來存儲索引,所以我知道e字段,我也希望能夠獲得點擊的字段。
請我想知道是否 queryParser parse = queryParser(「fie ld」,query); 可以執行所有類型的lucene查詢,還是必須從查詢字符串中識別查詢的類型以調用appropraite查詢類型方法。我不想在設計上加強我的代碼中的錯誤。如果任何整潔的方式來結合所有的查詢類型,它可以幫助我很多。 我仍然是一個初學者與lucene搜索 –