Lucene 6.0中的TermQuery和QueryParser有什么区别?

时间:2016-11-07 14:28:23

标签: lucene

有两个查询,一个是QueryParser创建的:

QueryParser parser = new QueryParser(field, analyzer);
Query query1 = parser.parse("Lucene");

另一个是术语查询:

Query query2=new TermQuery(new Term("title", "Lucene"));

query1和query2有什么区别?

2 个答案:

答案 0 :(得分:8)

这是来自lucene docs的术语的定义。

A Term represents a word from text. This is the unit of search. It is composed of two elements, the text of the word, as a string, and the name of the field that the text occurred in.

因此,在您的情况下,将创建查询以搜索单词" Lucene"在该领域"标题"。

为了解释两者之间的区别让我采取不同的例子,

考虑以下

Query query2 = new TermQuery(new Term("title", "Apache Lucene"));

在这种情况下,查询将搜索确切的单词" Apache Lucene"在字段标题。

在另一种情况下     作为一个例子,让我们假设一个Lucene索引包含两个字段," title"和"身体"。

QueryParser parser = new QueryParser("title", "StandardAnalyzer");
Query query1 = parser.parse("title:Apache body:Lucene");
Query query2 = parser.parse("title:Apache Lucene");
Query query3 = parser.parse("title:\"Apache Lucene\"");
几件事。

  1. "标题"是QueryParser将搜索的字段,如果您不在其前面添加字段。(如构造函数中所示)。
  2. parser.parse("title:Apache body:Lucene"); - >在这种情况下,最终查询将如下所示。 query2 = title:Apache body:Lucene。
  3. parser.parse("body:Apache Lucene"); - >在这种情况下,最终查询也将如下所示。 query2 = body:Apache标题:Lucene。但出于不同的原因。

    因此解析器将搜索" Apache"在身体领域和" Lucene"在标题字段中。 由于该字段仅对其直接位于之前的字词有效,(http://lucene.apache.org/core/2_9_4/queryparsersyntax.html

    因为我们没有为lucene指定任何字段,所以默认字段为" title"将被使用。

  4. query2 = parser.parse("title:\"Apache Lucene\"");在这种情况下,我们明确告诉我们要搜索" Apache Lucene"在现场"标题"。这是短语查询,如果分析正确,则类似于术语查询。

  5. 因此,总结一下术语查询不会分析术语并按原样搜索。而Query解析器根据上述某些条件解析输入。

答案 1 :(得分:4)

QueryParser解析字符串并构建BooleanQuery(afaik),其中包含BooleanClausesanalyzes条款。

TermQuery不进行分析,并按原样使用该术语。这是主要的区别。

因此query1query2可能与我相同(在某种意义上,它们提供相同的搜索结果)field是相同的,而QueryParser' s analyzer并未改变该术语。

相关问题