Lucene:具有多个字段的查询和文档

时间:2011-02-28 12:57:21

标签: java lucene

我有一组包含多个字段的文档,我需要使用来自多个字段的多个术语执行查询。

你建议我用什么? MultiFieldQueryParser或MultiPhraseQuery?

感谢

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

分析器的选择

首先,注意您使用的是哪种分析仪。我被困了一段时间才意识到StandardAnalyzer过滤掉常见词语,例如''并且' a'。当您的字段值为' A'时,这是一个问题。您可能需要考虑KeywordAnalyzer:

See this post around the analyzer.

// Create an analyzer:
// NOTE: We want the keyword analyzer so that it doesn't strip or alter any terms:
// In our example, the Standard Analyzer removes the term 'A' because it is a common English word.
// https://stackoverflow.com/a/9071806/231860
KeywordAnalyzer analyzer = new KeywordAnalyzer();

Query Parser

接下来,您可以使用QueryParser创建查询:

See this post around overriding the default operator.

// Create a query parser without a default field in this example (the first argument):
QueryParser queryParser = new QueryParser("", analyzer);

// Optionally, set the default operator to be AND (we leave it the default OR):
// https://stackoverflow.com/a/9084178/231860
// queryParser.setDefaultOperator(QueryParser.Operator.AND);

// Parse the query:
Query multiTermQuery = queryParser.parse("field_name1:\"field value 1\" AND field_name2:\"field value 2\"");

查询API

或者您可以通过自己使用API​​构建查询来实现相同目的:

See this tutorial around creating the BooleanQuery.

BooleanQuery multiTermQuery = new BooleanQuery();
multiTermQuery.add(new TermQuery(new Term("field_name1", "field value 1")), BooleanClause.Occur.MUST);
multiTermQuery.add(new TermQuery(new Term("field_name2", "field value 2")), BooleanClause.Occur.MUST);

删除与查询匹配的文档

然后我们最终将查询传递给编写器以删除与查询匹配的文档:

See my answer here, related to this answer.

See the answer to this question.

// Remove the document by using a multi key query:
// http://www.avajava.com/tutorials/lessons/how-do-i-combine-queries-with-a-boolean-query.html
writer.deleteDocuments(multiTermQuery);