java - 如何使用 lucene 索引查询国家代码?

标签 java lucene

我正在为城市名称和国家代码(相互依赖)创建一个 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/

相关文章:

java - Apache Solr - 为什么分片索引的结果分数与非分片索引的结果分数不同?

elasticsearch - 在 Elasticsearch 中将字段映射到类型有哪些优点?

c# - Lucene - 搜索数值字段

java - Jdo错误重复键

java - 如何使用最新版本的计费客户端正确导入 BillingResponse (billing :2. 0.1)

java - Android 内存不足错误位图

java - 为什么这个流不返回任何元素?

java - 是否可以借助注释在我自己的代码之外编写代码?

java - Lucene 查询范围

Python文件索引和搜索