如何在 Lucene 中进行多字段 - 短语搜索?

2022-01-15 00:00:00 lucene java

标题问一切...我想在 Lucene 中进行多字段短语搜索.. 怎么做?

Title asks it all... I want to do a multi field - phrase search in Lucene.. How to do it ?

例如:我的字段为 String s[] = {"title","author","content"};
我想在所有领域搜索 harry potter.我该怎么做?

for example : I have fields as String s[] = {"title","author","content"};
I want to search harry potter across all fields.. How do I do it ?

有人可以提供一个示例片段吗?

Can someone please provide an example snippet ?

推荐答案

  1. 使用 MultiFieldQueryParser,它的 一个 QueryParser 构造查询以搜索多个字段..

其他方法是使用创建一个由 TermQurey 组成的 BooleanQuery(在您的情况下是短语查询).

Other way is to use Create a BooleanQuery consisting of TermQurey (in your case phrase query).

第三种方法是将其他字段的内容包含到您的 default 内容字段中.

Third way is to include the content of other fields into your default content field.

<小时>添加

一般来说,查询多个字段并不是用户输入查询的最佳做法.更常见的是,您想要搜索的所有单词都通过组合各种字段被索引到内容或关键字字段中.<小时>更新

Generally speaking, querying on multiple fields isn’t the best practice for user-entered queries. More commonly, all words you want searched are indexed into a contents or keywords field by combining various fields.


Update

用法:

Query query = MultiFieldQueryParser.parse(Version.LUCENE_30, new String[] {"harry potter","harry potter","harry potter"},   new String[] {"title","author","content"},new SimpleAnalyzer());
IndexSearcher searcher = new IndexSearcher(...);
Hits hits = searcher.search(query);

MultiFieldQueryParser 将以这种方式解析查询:(参见 javadoc)

The MultiFieldQueryParser will resolve the query in this way: (See javadoc)

解析在指定的字段.如果 x 字段是指定,这有效构造:

Parses a query which searches on the fields specified. If x fields are specified, this effectively constructs:

(field1:query1) (field2:query2)(field3:query3)...(fieldx:queryx)

(field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx)

希望这会有所帮助.

相关文章