ES Join是Elasticsearch中的一个非常重要的功能,它可以将多个Index之间的数据进行关联查询。本文将从多个方面对ES Join进行详细阐述。
一、如何进行ES Join
ES Join可以通过在Mapping中定义Parent-Child Relationship来实现,具体步骤如下:
PUT /my_index
{
  "mappings": {
    "parent": {},
    "child": {
      "_parent": {"type": "parent"}          
    }
  }
}
PUT /my_index/parent/1
{
  "name": "Parent Document"
}
PUT /my_index/child/2?parent=1
{
  "name": "Child Document"
}
由上述例子可以看出,定义一个Parent/Child关系需要在Mapping中定义一个类型为“parent”的Mapping,另一个类型为“child”的Mapping中需要定义一个”_parent”字段,并指定它的类型为“parent”。在实际插入数据时,需要通过“parent”字段来绑定父子关系。
二、ES Join的类型
ES Join可以分为两种类型:查询父文档和查询子文档。
1.查询父文档
查询父文档可以通过后缀为“_parent”的相关查询来实现。
GET /my_documents/_search
{
    "query": {
        "has_parent": {
            "parent_type": "parent", 
            "query": {
                "match_all": {}
            }
        }
    }
}
上述例子中,通过”has_parent”查询来查询Parent文档。其中,”parent_type”指定了需要查询Parent对象的类型。具体查询的条件可以在”query”字段中指定。
2.查询子文档
查询子文档可以通过后缀为“_child”的相关查询来实现。
GET /my_documents/_search
{
    "query": {
        "has_child": {
            "type": "child",
            "query": {
                "match_all": {}
            }
        }
    }
}
上述例子中,通过“has_child”查询来查询Child文档。其中,“type”指定了需要查询Child对象的类型。具体查询的条件可以在“query”字段中指定。
三、ES Join的性能优化
在使用ES Join的过程中,为了获得更好的性能,需要使用以下方法来进行优化:
1.使用代理字段
代理字段是一种在Parent或Child Type上定义,用于存储和访问关联文档反向关系的字段。使用代理字段优化ES Join查询时,我们可以在Parent或Child Type上定义代理字段,例如下面这个例子:
PUT index
{
  "mappings": {
    "parent": {
      "properties": {
        "name": {"type":"text"}
      }
    },
    "child": {
      "_parent": {"type": "parent"},
      "properties": {
        "name": {"type":"text"},
        "parent_name": {
          "type": "text",
          "store": true,
          "fielddata": true,
          "index": false
        }
      }
    }
  }
}
在上述例子中,Child Type上定义了一个名为”parent_name”的代理字段,通过设置”store”和”fielddata”参数来决定该字段是否需要进行聚合分析。当需要通过子文档检索父文档时,可以通过代理字段来关联查询。
2.使用Top Children进行查询优化
Top Children查询是一种使用ES Join优化查询性能的方法。它通过在查询时执行父子关系字段匹配操作,从而只返回相关文档的子集。下面是一个Top Children查询的例子:
GET /my_index/child/_search
{
    "query": {
        "top_children": {
            "type": "parent", 
            "query": {
                "match_all": {}
            },
            "score": "none"
        }
    }
}
在上述例子中,使用“top_children”查询来进行查询优化。其中,“type”指定了需要查询Parent对象的类型。具体查询的条件可以在“query”字段中指定。指定“score”为”none”时,将减少计算。
四、总结
以上是ES Join的一些重要特性及优化方法的介绍。合理使用ES Join可以提高查询效率,从而更好地服务用户的需求。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/289193.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 