elasticsearch的join查询

时间:2021-06-22 14:24:49

1.概述

官方文档

https://www.elastic.co/guide/en/elasticsearch/reference/current/joining-queries.html

两种类型的查询

嵌套查询

has_child和has_parent

其中,has_child返回包含特定查询字段文档的父文档;

has_parent返回包含特定查询字段的父文档的子文档。

2.实例

2.1 嵌套查询

GET /_search
{
"query": {
"nested" : {
"path" : "obj1",
"score_mode" : "avg",
"query" : {
"bool" : {
"must" : [
{ "match" : {"obj1.name" : "blue"} },
{ "range" : {"obj1.count" : {"gt" : 5}} }
]
}
}
}
}
}

2.2 has_child 查询

GET /_search
{
"query": {
"has_child" : {
"type" : "blog_tag",
"query" : {
"term" : {
"tag" : "something"
}
}
}
}
}

2.3 has_parent

GET /_search
{
"query": {
"has_parent" : {
"parent_type" : "blog",
"query" : {
"term" : {
"tag" : "something"
}
}
}
}
}

2.4 parent_id 查询

PUT my_index
{
"mappings": {
"_doc": {
"properties": {
"my_join_field": {
"type": "join",
"relations": {
"my_parent": "my_child"
}
}
}
}
}
} PUT my_index/_doc/1?refresh
{
"text": "This is a parent document",
"my_join_field": "my_parent"
} PUT my_index/_doc/2?routing=1&refresh
{
"text": "This is a child document",
"my_join_field": {
"name": "my_child",
"parent": "1"
}
}
GET /my_index/_search
{
"query": {
"parent_id": {
"type": "my_child",
"id": "1"
}
}
}