ES RequestBodySearch - nested
2020-03-13 本文已影响0人
天高s
nested 查询
es 默认会把字段拍平, 举个栗子,比如下面这样的数据:
PUT book/_doc/1
{
"title": "elasticsearch入门",
"author": [
{
"first_name": "Andy", "last_name": "William"
},
{
"first_name": "Jack", "last_name": "Smith"
}
]
}
如果我们查找 Andy Smith
写的书
GET book/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"author.first_name": "Andy"
}
},
{
"match": {
"author.last_name": "Smith"
}
}
]
}
}
}
返回的结果
{
"took" : 10,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.5753642,
"hits" : [
{
"_index" : "book",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.5753642,
"_source" : {
"title" : "elasticsearch入门",
"author" : [
{
"first_name" : "Andy",
"last_name" : "William"
},
{
"first_name" : "Jack",
"last_name" : "Smith"
}
]
}
}
]
}
}
显然是不对的,first_name
和 last_name
应该是绑定在一起的属性,所以就需要定义 nested
属性
PUT book
{
"mappings" : {
"properties" : {
"author" : {
"type": "nested",
"properties" : {
"first_name" : {
"type" : "keyword"
},
"last_name" : {
"type" : "keyword"
}
}
},
"title" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
查询的语句也有变化
GET book/_search
{
"query": {
"bool": {
"must": {
"nested": {
"path": "author",
"query": {
"bool": {
"must": [
{ "match": { "author.first_name": "Andy" } },
{ "match": { "author.last_name": "William" } }
]
}
}
}
}
}
}
}
这样就对了