请原谅我的新手问题。我曾尝试搜索答案,但考虑到关键字,搜索此类内容非常困难...
我正在使用 Lucene 5.2.x 来索引一组文档,每个文档都有两个字段:id
和 description
。
我从系统中的先前查询中获得了一组 ids
。现在,我想获取有关 description
的 Lucene 文本搜索结果,但只能来自 ids
集合中的文档。如果我在 MySQL 中(天真地)这样做,我可能会做类似的事情:
SELECT * FROM mytable
WHERE description LIKE 'blah%'
AND
id IN (6345, 5759, 333, ...)
ids
的集合可能有数万个。使用 Lucene 的最佳方法是什么?我可以构造一个 Lucene 查询来有效地处理这个问题,还是应该搜索我的整个文档索引然后进行集合交集?还有别的吗?
谢谢!
最佳答案
I would like to get Lucene text search results on the description but only from documents in the set of
ids
.
您需要使用BooleanQuery
。
如果您使用 QueryParser
创建查询,则使用:
+(id:6345 id:5759 id:333 ...) +(description:"blah*")
如果您以编程方式创建查询
,那么代码将类似于:
BooleanQuery ids = new BooleanQuery();
ids.add(new TermQuery(new Term("id", "6345")), SHOULD);
ids.add(new TermQuery(new Term("id", "5759")), SHOULD);
ids.add(new TermQuery(new Term("id", "333")), SHOULD);
BooleanQuery resultQuery = new BooleanQuery();
resultQuery.add(new PrefixQuery(new Term("description", "blah")), MUST);
resultQuery.add(ids, MUST);
The set of
ids
maybe tens of thousands.
BooleanQuery
已将其限制为子句的最大数量(请参阅 org.apache.lucene.search.BooleanQuery#maxClauseCount
)。您需要使用 BooleanQuery.setMaxClauseCount()
增加此限制。这将要求您以编程方式创建查询。
Can I construct a Lucene query to handle this efficiently, or should I search my entire document index and then do a set intersection? Something else?
据我所知,倒排索引是目前人类已知的最高效的搜索方式。至少,从搜索时间的角度来看(不考虑索引阶段)。
因此,如果关注效率,我建议将所有搜索逻辑移至 Lucene(倒排索引库)。作为一个非常成熟的库,Lucene 可以搜索几乎所有类型的信息。因此,可能您的所有文档都可以在 Lucene 中建立索引,并且所有“先前的查询”也可以在 Lucene 中执行。
在那种情况下,就没有必要将数千个 id 作为附加过滤器发送到 Lucene,这确实看起来很浪费。除非您有一些独特的搜索要求,否则这是我能想到的最有效的搜索方式。
关于java - Lucene - 相当于 SQL "IN"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31029351/