ElasticSearch Parent-Child结构

Parent-Child关系主要用来处理一对多关系。6.x开始es废弃了一个索引中多个type的模式,6.x中一个索引只能有一个type,7.x废除type。因此不再使用_parent标签。

版本

6.8

ElasticSearch官网

设置索引

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "my_join_field": { 
          "type": "join",
          "relations": {
            "question": "answer" 
          }
        }
      }
    }
  }
}

//多个child
PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "my_join_field": {
          "type": "join",
          "relations": {
            "question": ["answer", "comment"]  
          }
        }
      }
    }
  }
}

//多层级
PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "my_join_field": {
          "type": "join",
          "relations": {
            "question": ["answer", "comment"],  
            "answer": "vote" 
          }
        }
      }
    }
  }
}
复制代码

更新数据

添加单条Parent数据

PUT my_index/_doc/1
{
  "text": "This is a question",
  "my_join_field": {
    "name": "question" 
  }
}
复制代码

批量添加Parent数据

POST _bulk
{"index":{"_index":"my_index","_type":"_doc","_id":"bulk-1"}}
{"text":"bulk questions","my_join_filed":{"name":"question"}}
复制代码

添加单条child数据

添加时要使用routing来保证添加到制定的parent中

PUT my_index/_doc/3?routing=1
{
  "text": "This is an answer",
  "my_join_field": {
    "name": "answer", 
    "parent": "1" 
  }
}
复制代码

无法使用bulk来批量新增child数据。es会将my_join_field识别为一个对象,而不是Parent-Child关系特有的值

查询

查询child

通过has_parent查询child

GET my_index/_search
{
  "query": {
    "has_parent": {
      "parent_type": "question",
      "query": {
        "match": {
          "text": "this is"
        }
      }
    }
  }
}
复制代码

通过parent_id查询child

GET /my_index/_search
{
  "query": {
    "parent_id": {
      "type": "answer",
      "id": "2"
    }
  }
}
复制代码

查询parent

通过has_child查询parent

GET my_index/_search
{
  "query": {
    "has_child": {
      "type": "answer",
      "min_children": 1, //可选值,查询至少有1个child的parent
      "max_children": 10,//可选值,查询最多有10个child的parent
      "query": {
        "match": {
          "text": "this is"
        }
      }
    }
  }
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享