在 Lucene 中一起搜索由 AND 条件分隔的 TextField 和 IntField

Searching a TextField and IntField together seperated by an AND condition In Lucene

我已将我的文档编入索引:

doc.add(new IntField("ID", id, Field.Store.YES));
doc.add(new TextField("First_Name", First_Name, Field.Store.YES));
doc.add(new TextField("Last_Name", Last_Name, Field.Store.YES));
doc.add(new TextField("Address", add, Field.Store.YES));
doc.add(new TextField("City", city, Field.Store.YES));
doc.add(new TextField("State", state, Field.Store.YES));
doc.add(new IntField("Zip_Code", zip, Field.Store.YES));

其中 id、FirstName、city、add、state、zip 是存储要索引的值的变量。

我想在索引上搜索 "ID:someValue AND First_Name:SomeValue" 但由于int字段和string字段的查询解析器不同,我无法这样做。

我正在搜索文档:

Query query = queryParser.parse(searchQuery);
TopScoreDocCollector collector=TopScoreDocCollector.create(LuceneConstants.MAX_SEARCH); 
indexSearcher.search(query, collector );

对于整数值:

query = NumericRangeQuery.newIntRange(field, searchTerm, searchTerm , true, true);        
TopScoreDocCollector collector = TopScoreDocCollector.create(LuceneConstants.MAX_SEARCH);
indexSearcher.search(query, collector );

我如何使用单个查询分析器,使其可以同时处理文本和数字值?如何使用单个查询来搜索此类查询?

有几种可能性。

首先,在这种情况下我最推荐的是,也许您根本不需要那些 IntField。邮政编码和 ID 通常不被视为数字。它们是恰好由数字组成的标识符。如果您的邮政编码是 23456,这并不意味着您居住在第 23,456 个邮政编码中。它只是一串任意数字。如果使用数字范围搜索字段没有用,您可能应该将其设为 StringField(或 TextField)。

不过,如果您真的希望它成为一个 IntField,您可以跳过解析器。只需使用 API 构建您的查询:

BooleanQuery query = new BooleanQuery();
query.add(new BooleanClause(NumericRangeQuery.newIntRange("ID", myIdValue, myIdValue, true, true), BooleanClause.Occur.MUST));
query.add(new BooleanClause(new TermQuery(new Term("First_Name", myNameValue)), BooleanClause.Occur.MUST));