Elasticsearch 链接查询

在通常的关系型数据库中,都支持链接操做。html

在ES这种分布式方案中进行链接操做,代价是十分昂贵的。数据库

不过ES也提供了相相似的操做,支持水平任意扩展,实现链接的效果。数组

其余内容,参考Elasticsearch官方指南整理app

ES中的链接

在ES中支持两种链接方式:嵌套查询 has_child、has_parent父子查询elasticsearch

嵌套查询:分布式

文档中包含嵌套的字段,这些字段以数组的形式保存对象,这样每一个嵌套的子对象均可以被搜索。ide

has_child、has_parent父子查询:ui

父子文档是存储在同一个索引中的不一样类型,在索引数据前定义父子关系。在父子查询中,父子关系经过类型引用。spa

嵌套查询

嵌套类型须要实现定义好mapping:code

{ "type1" : { "properties" : { "obj1" : { "type" : "nested" } } } }

定义好后,type1中就有了obj1这个子对象,而后就能够经过嵌套查询查询相关的内容:

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

注意其中几个参数:

1 path 定义了嵌套的对象

2 score_mode 定义里嵌套对象计算的分数与当前查询分数的处理方式,有avg,sum,max,min以及none。none就是不作任何处理,其余的看字面意思就好理解。

3 query/filter是查询的方式,内部定义了针对嵌套对象的查询,注意内部的查询必定要是用全路径,即针对obj1的name字段的查询,要写obj1.name。

嵌套查询会在执行子查询的时候自动触发,而后把结果返回给当前文档的查询。

 

父子查询

父子关系也须要在以前定义mapping,不过与通常的映射不一样,它的定义方式以下:

PUT my_index { "mappings": { "my_parent": {}, "my_child": { "_parent": { "type": "my_parent" } } } } PUT my_index/my_parent/1 { "text": "This is a parent document" } PUT my_index/my_child/2?parent=1 { "text": "This is a child document" } PUT my_index/my_child/3?parent=1 { "text": "This is another child document" } GET my_index/my_parent/_search { "query": { "has_child": { "type": "my_child", "query": { "match": { "text": "child document" } } } } }

这样就表明,my_child这个类型的父类型是my_parent,这样就声明了一种父子关系。而后再索引数据时,指定父子对应的关系。

has_child查询

这个查询会检查子文档,若是子文档知足查询条件,则返回父文当。

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

经过score_mode字段,能够指定子文档返回的分值的处理方式。与嵌套相似,它也有avg,sum,max,min和none几种方式。

{ "has_child" : { "type" : "blog_tag", "score_mode" : "sum", "query" : { "term" : { "tag" : "something" } } } }

另外,也能够指定子文档匹配的最小数目和最大数目。

{ "has_child" : { "type" : "blog_tag", "score_mode" : "sum", "min_children": 2, "max_children": 10, "query" : { "term" : { "tag" : "something" } } } }

has_parent查询

has_parent查询与has_child相似,它是去检查父文档那个是否匹配,而后返回父文档对应的子文档。

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

 

参考

1 如何定义父子关系:https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-parent-field.html

2 链接查询:https://www.elastic.co/guide/en/elasticsearch/reference/current/joining-queries.html

3 Nested查询:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

4 Has_Child查询:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-has-child-query.html

5 Has_Parent查询:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-has-parent-query.html

相关文章
相关标签/搜索