这是一种似乎可以实现您想要的方法:http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443 http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443
首先,我创建了一个具有显式映射的索引。我这样做是为了我可以设置"tags"
财产给"index": "not_analyzed"
。这意味着文本不会以任何方式修改,这将简化本示例的查询过程。
curl -XPUT "http://localhost:9200/test_index" -d'
{
"mappings": {
"docs" : {
"properties": {
"tags" : {
"type": "string",
"index": "not_analyzed"
},
"label" : {
"type": "string"
}
}
}
}
}'
然后添加一些文档:
curl -XPUT "http://localhost:9200/test_index/docs/1" -d'
{
"tags" : [
"tag-1",
"tag-2",
"tag-3",
"tag-A"
],
"label" : "item 1"
}'
curl -XPUT "http://localhost:9200/test_index/docs/2" -d'
{
"tags" : [
"tag-1",
"tag-2",
"tag-3"
],
"label" : "item 2"
}'
curl -XPUT "http://localhost:9200/test_index/docs/3" -d'
{
"tags" : [
"tag-1",
"tag-2"
],
"label" : "item 3"
}'
然后我们可以使用查询must
and must_not
a 中的条款bool
过滤如下:
curl -XPOST "http://localhost:9200/test_index/_search" -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"terms": {
"tags": [
"tag-1",
"tag-2",
"tag-3"
],
"execution" : "and"
}
}
],
"must_not": [
{
"term": {
"tags": "tag-A"
}
}
]
}
}
}
}
}'
这会产生正确的结果:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "test_index",
"_type": "docs",
"_id": "2",
"_score": 1,
"_source": {
"tags": [
"tag-1",
"tag-2",
"tag-3"
],
"label": "item 2"
}
}
]
}
}
注意"execution" : "and"
中的参数terms
过滤在must
条款。这意味着只有具有所有"tags"
将返回指定的内容(而不是那些匹配一个或多个的内容)。这可能正是您所缺少的。您可以阅读有关选项的更多信息ES docs http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html.
我做了一个可以运行的例子here http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443如果你安装了 ES 并且运行在localhost:9200
,或者您可以提供自己的端点。