我正在为城市名和乡村代码创建一个lucene索引(取决于彼此)。我希望乡村代码是小写的可搜索和完全匹配。
首先,我现在尝试查询单个国家/地区代码并查找与该代码匹配的所有索引元素。我的结果总是空的。
//prepare
VERSION = Version.LUCENE_4_9;
IndexWriterConfig config = new IndexWriterConfig(VERSION, new SimpleAnalyzer());
//index
Document doc = new Document();
doc.add(new StringField("countryCode", countryCode, Field.Store.YES));
writer.addDocument(doc);
//lookup
Query query = new QueryParser(VERSION, "countryCode", new SimpleAnalyzer()).parse(countryCode);
结果:
当我查询诸如“IT”,“DE”,“EN”等的coutrycodes时,结果始终为空。为什么?
对于2个字母的国家/地区代码是SimpleAnalyzer
吗?
答案 0 :(得分:2)
对于 StringField ,您可以使用 TermQuery 代替 QueryParser
Directory dir = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9, new SimpleAnalyzer(Version.LUCENE_4_9));
IndexWriter writer = new IndexWriter(dir, config);
String countryCode = "DE";
// index
Document doc = new Document();
doc.add(new StringField("countryCode", countryCode, Store.YES));
writer.addDocument(doc);
writer.close();
IndexSearcher search = new IndexSearcher(DirectoryReader.open(dir));
//lookup
Query query = new TermQuery(new Term("countryCode", countryCode));
TopDocs docs = search.search(query, 1);
System.out.println(docs.totalHits);
答案 1 :(得分:1)
我在这里有点困惑。我假设您的索引编写器已在未提供的代码的某些部分初始化,但您是否羞于将Version
传递到SimpleAnalyzer
? SimpleAnalyzer
没有arg构造函数,无论如何都不是3.X.
这是我看到的唯一真正的问题。以下是使用代码的工作示例:
private static Version VERSION;
public static void main(String[] args) throws IOException, ParseException {
//prepare
VERSION = Version.LUCENE_4_9;
Directory dir = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(VERSION, new SimpleAnalyzer(VERSION));
IndexWriter writer = new IndexWriter(dir, config);
String countryCode = "DE";
//index
Document doc = new Document();
doc.add(new TextField("countryCode", countryCode, Field.Store.YES));
writer.addDocument(doc);
writer.close();
IndexSearcher search = new IndexSearcher(DirectoryReader.open(dir));
//lookup
Query query = new QueryParser(VERSION, "countryCode", new SimpleAnalyzer(VERSION)).parse(countryCode);
TopDocs docs = search.search(query, 1);
System.out.println(docs.totalHits);
}