2016-07-05 103 views
1

目前正在开发使用elasticsearch标签搜索应用程序,我已经给了该指数中的每个文档的标签数组,这里有一个文档外观的例子:Elasticsearch匹配给定的数组内的所有标签

_source: { 
    title: "Keep in touch scheme", 
    intro: "<p>hello this is a test</p> ", 
    full: " <p>again this is a test mate</p>", 
    media: "", 
    link: "/training/keep-in-touch", 
    tags: [ 
    "employee", 
    "training" 
    ] 
} 

我会喜欢能够进行搜索,并且只能返回包含所有指定标签的文档。

使用上面的示例,如果我搜索了带有标签["employee", "training"]的文档,则会返回上述结果。

相反,如果我使用标签["employee", "other"]进行搜索,则不会返回任何内容;搜索查询中的所有标签都必须匹配。

目前我做的:

query: { 
    bool: { 
    must: [ 
     { match: { tags: ["employee","training"] }} 
    ] 
    } 
} 

但我刚刚返回例外像

IllegalStateException[Can't get text on a START_ARRAY at 1:128]; 

我也试图串联阵列和用逗号分隔的字符串,然而,这似乎符合任何给予第一个标签的匹配。

关于如何解决这个问题的任何建议?干杯

回答

1

选项1:下一个例子就可以(V2.3.2):

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{ 
    "query": { 
    "bool": { 
     "must": [ 
     { "term": { "tags": "employee" } } , 
     { "term": { "tags": "training" } } 
     ] 
    } 
    } 
}' 

选项2:你也可以试试:

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{ 
    "query": { 
    "filtered": { 
     "query": {"match_all": {}}, 
     "filter": { 
     "terms": { 
      "tags": ["employee", "training"] 
     } 
     } 
    } 
    } 
}' 

但是,如果没有"minimum_should_match": 1它的工作原理有点bin不准确。 我也发现"execution": "and"但它工作不准确。

方案3:另外你的猫尝试query_string它完美,但看起来有点复杂:

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{ 
"query" : { 
    "query_string": { 
     "query": "(tags:employee AND tags:training)" 
    } 
    } 
}' 

也许这将是对你有帮助...

+0

这个问题是标签可以改变量,它并不总是2 - 理想的情况下,我可以通过不同长度的查询 –

+0

数组@ WilliamPaul我已经添加了另一个例子,但我无法找到解决方案如何在es v2.3.2中使用''minimum_should_match“:1' ... –

+0

@WilliamPaul我还添加了'query_string'的例子。 –

0

为了确保集仅包含指定的值,维护辅助字段以跟踪标签数量。然后你就可以查询像下面得到想要的结果

"query":{ 
    "bool":{ 
     "must":[ 
      {"term": {"tags": "employee"}}, 
      {"term": {"tags": "training"}}, 
      {"term": {"tag_count": 2}} 
     ] 
    } 
} 
相关问题