我正在为城市名称和国家代码(相互依赖)创建一个 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”等国家代码时,结果始终为空。为什么?
SimpleAnalyzer
是来自 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);
关于java - 如何使用 lucene 索引查询国家代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084407/