现在来看看另一个示例,搜索“drama”,不明确指定字段,如下查询
curl -XPOST "http://localhost:9200/_search" -d'
{
"query": {
"query_string": {
"query": "drama"
}
}
}'
因为在索引中有五部电影在_all字段(从类别字段)中包含单词“drama”,所以得到了上述查询的5个命中。 现在,想象一下,如果我们想限制这些命中为只是1962年发布的电影。要做到这点,需要应用一个过滤器,要求“year”字段等于1962。
要添加过滤器,修改搜索请求正文,以便当前的顶级查询(查询字符串查询)包含在过滤的查询中:
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "drama"
}
},
"filter": {
//Filter to apply to the query
}
}
}
}
过滤的查询是具有两个属性(query和filter)的查询。执行时,它使用过滤器过滤查询的结果。要完成这样的查询还需要添加一个过滤器,要求year字段的值为1962。
ElasticSearch查询DSL有各种各样的过滤器可供选择。对于这个简单的情况,某个字段应该匹配一个特定的值,一个条件过滤器就能很好地完成工作。
"filter": {
"term": { "year": 1962 }
}
完整的搜索请求如下所示:
curl -XPOST "http://localhost:9200/_search" -d'
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "drama"
}
},
"filter": {
"term": { "year": 1962 }
}
}
}
}'
当执行上面请求,只得到两个命中,这个两个命中的数据的 year 字段的值都是等于 1962。
在上面的示例中,使用过滤器限制查询字符串查询的结果。如果想要做的是应用一个过滤器呢? 也就是说,我们希望所有电影符合一定的标准。
在这种情况下,我们仍然在搜索请求正文中使用“query”属性。但是,我们不能只是添加一个过滤器,需要将它包装在某种查询中。
一个解决方案是修改当前的搜索请求,替换查询字符串 query 过滤查询中的match_all查询,这是一个查询,只是匹配一切。类似下面这个:
curl -XPOST "http://localhost:9200/_search" -d'
{
"query": {
"filtered": {
"query": {
"match_all": {
}
},
"filter": {
"term": { "year": 1962 }
}
}
}
}'
另一个更简单的方法是使用常数分数查询:
curl -XPOST "http://localhost:9200/_search" -d'
{
"query": {
"constant_score": {
"filter": {
"term": { "year": 1962 }
}
}
}
}'