多域查询也就是相当于多个字段查询
package com.baifan.lucene.index;
import com.baifan.lucene.ik.IKAnalyzer6x;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 多域查询
*/
public class MultiFieldQueryParseTest {
public static void main(String[] args)
throws ParseException, IOException {
String[] fields = {"title", "content"};
Path indexPath = Paths.get("indexdir");
Directory dir = FSDirectory.open(indexPath);
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
//使用智能分词
Analyzer analyzer = new IKAnalyzer6x(true);
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
Query query = parser.parse("美国"); // 查询关键词
System.out.println("Query:" + query.toString());
// 返回前10条
TopDocs tds = searcher.search(query, 10);
for (ScoreDoc sd : tds.scoreDocs) {
Document doc = searcher.doc(sd.doc);
System.out.println("DocID:" + sd.doc);
System.out.println("id:" + doc.get("id"));
System.out.println("title:" + doc.get("title"));
System.out.println("文档评分:" + sd.score);
}
dir.close();
reader.close();
}
}
运行结果:
加载扩展词典:ext.dic
加载扩展停止词典:stopword.dic
加载扩展停止词典:ext_stopword.dic
Query:title:美国 content:美国
DocID:2
id:3
title:XXXXXXXXXXXXX
文档评分:1.1645867
DocID:0
id:1
title:XXXXXXXXXXXXXXXX
文档评分:0.84453815