【发布时间】:2017-06-05 21:27:42
【问题描述】:
我正在构建一个可以生成自定义查询以搜索 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 文件创建动态字段并使用它来存储索引,因此我知道这些字段,并且我还希望能够获得命中的字段。
【问题讨论】:
-
我想知道 queryParser parse= queryParser("fie ld", query);可以执行所有类型的 lucene 查询,还是我必须从查询字符串中识别查询类型才能调用适当的查询类型方法。我不想在我的代码中过度设计增强错误。如果有任何巧妙的方法来组合所有查询类型,它可以帮助我很多。我仍然是 lucene 搜索的初学者