如何在Elasticsearch的对象数组中的同一对象内搜索字段? [英] How do i search for fields inside a same object in an array of objects in elasticsearch?
问题描述
我维护了一个对象数组,其中包含几个对象,每个对象都有两个键,但是每个对象中这些键的值不同,我想对每个对象运行范围查询以及match_phrase查询,但是正在发生的事情是正确的现在是,如果一个键通过第一个对象中的match_phrase进行匹配,而另一个键通过第二个对象的范围查询进行了匹配,则两者都出现在结果中,但我想分别为每个对象运行两个查询.
I have maintained one array of objects field which contains several objects, having two keys each but different values for those keys in each object and i want to run a range query along with a match_phrase query on each object but what is happening right now is that if a key is matched via match_phrase in 1st object and an other key is matched via the range query of 2nd object then both appear in result but i want to run both the queries respectively for each object.
第一个POST请求:
POST test/_doc
{
"name": "yash",
"score": [
{
"model" : "swift",
"score" : 5
},
{
"model" : "alto",
"score" : 6
},
{
"model" : "xuv",
"score" : 9
}
]
}
搜索查询:
GET test/_search
{
"query": {
"bool": {
"must": [
{
"match_phrase": {
"score.model": "swift"
}
},
{
"range": {
"score.score": {
"gte": 6,
"lte": 9
}
}
}
]
}
}
}
实际结果:
"_index" : "test",
"_type" : "_doc",
"_id" : "g1LA12wBeamdnjKY5k-N",
"_score" : 1.287682,
"_source" : {
"name" : "yash",
"score" : [
{
"model" : "swift",
"score" : 5
},
{
"model" : "alto",
"score" : 6
},
{
"model" : "xuv",
"score" : 9
}
]
}
预期结果:
什么都没有,因为迅速的分数范围不符合指定的值.
Nothing as the range of score in swift is not according to the specified value.
推荐答案
您需要将得分
字段定义为嵌套
:
PUT test
{
"mappings": {
"properties": {
"score": {
"type": "nested"
}
}
}
}
您还可以通过使用动态映射来动态创建嵌套字段,该映射会将所有对象转换为嵌套
类型:
You can also create the nested field dynamically, by using a dynamic mapping that would transform all objects into nested
type:
PUT test
{
"mappings": {
"dynamic_templates": [
{
"nested_objects": {
"match_mapping_type": "object",
"mapping": {
"type": "nested"
}
}
}
]
}
}
然后,您将能够使用嵌套
查询来查询该字段,并获得所需的结果:
Then you'll be able to query that field using a nested
query and get the result you expect:
POST test/_search
{
"query": {
"nested": {
"path": "score",
"query": {
"bool": {
"must": [
{
"match_phrase": {
"score.model": "swift"
}
},
{
"range": {
"score.score": {
"gte": 6,
"lte": 9
}
}
}
]
}
}
}
}
}
这篇关于如何在Elasticsearch的对象数组中的同一对象内搜索字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!