EleasticSearch6.0 巢狀查詢

baiyaoqiang發表於2020-04-29

1,新增索引
PUT /earth_index

{
  "mappings": {
    "earthblog": {
      "properties": {
        "title":{ "type":"string"},
        "body":{ "type":"string"},
        "comments": {
          "type": "nested", 
          "properties": {
            "name":    { "type": "string"  },
            "comment": { "type": "string"  },
            "age":     { "type": "short"   },
            "date":    { "type": "date"    }
          }
        }
      }
    }
  }
}

2,新建文件
PUT /earth_index/earthblog/1

{
  "title": "強大的搜尋引擎",
  "body":  "你好這是我的一條案例...",
  "comments": [ 
    {
      "name":    "小白",
      "comment": "very goods",
      "age":     23,
      "date":    "2020-04-29"
    },
    {
      "name":    "小黑",
      "comment": "More like this please",
      "age":     18,
      "date":    "2020-04-29"
    }
  ]
}

3,查詢出姓名為小白並且年齡23的資料
3.1 非巢狀查詢
GET /earth_index/earthblog/_search

{
  "query": {
    "bool": {
      "must": [
        { "match": { "comments.name": "小白" }},
        { "match": { "comments.age":  23 }} 
      ]
    }
  }
}

3.2 巢狀查詢
GET /earth_index/earthblog/_search

{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "comments.name": "小白"
              }
            },
            {
              "match": {
                "comments.age": 23
              }
            }
          ]
        }
      }
    }
  }
}
``````json
{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "comments.name": "小白"
              }
            },
            {
              "match": {
                "comments.age": 23
              }
            }
          ]
        }
      }
    }
  }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章