美文网首页
ES RequestBodySearch - nested

ES RequestBodySearch - nested

作者: 天高s | 来源:发表于2020-03-13 14:10 被阅读0次

    7.6 官方文档

    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_namelast_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" } }
                  ]
                }
              }
            }
          }
        }
      }
    }
    

    这样就对了

    相关文章

      网友评论

          本文标题:ES RequestBodySearch - nested

          本文链接:https://www.haomeiwen.com/subject/oskhshtx.html