ElasticSearch 6.x 父子文档[join]分析

ES6.0之后,索引的type只能有一个,使得父子结构变的不那么清晰,毕竟对于java开发者来讲,index->db,type->table的结构比较容易理解。java

按照官方的说明,以前一个索引有多个type,若是有一个相同的字段在不一样的type中出现,在ES底层实际上是按照一个field来作lucene索引的,这很具备迷惑性,容易形成误解。因此6.0之后,全部的字段都在索引的_doc【默认type】中集中定义。假设索引中会有parent和child两个类型的文档,那么可能parent引用了abcd字段,child引用了aef字段,各取所需。app

目前我用的es版本为6.3,父子结构须要用join字段来定义,关系的映射用relations字段来指定。spa

一个索引中只能有一个join类型字段,若是定义一个以上的join字段,会报错:Field [_parent_join] is defined twice in [_doc]
join字段中的relations集合,建好索引以后,能够增长映射,或者给原有的映射添加child,可是不能删除原有的映射。
好比,原有的relations定义为:code

"myJoin": {
  "type": "join",
  "eager_global_ordinals": true,
  "relations": {
    "parent_a": child_a1
  }
}

如今经过updateMapping API增长一条映射parent_b,原有的映射增长了child_a2child_a3blog

"myJoin": {
  "type": "join",
  "eager_global_ordinals": true,
  "relations": {
    "parent_a": [
      "child_a1",
      "child_a2",
      "child_a3"
    ],
    "parent_b": "child_b"
  }
}

 中午睡了个午觉,接着再写一点join的操做排序

  • 根据子文档查询父文档
GET /test_index_join/_search
{
  "query": {
    "has_child": {
      "type": "child_a1",
      "score_mode": "max", 
      # 基于child_a1文档定义来搜索,query里的查询字段是child_a1里的
      "query": {
        "term": {
          "salesCount": 100
        }
      }
    }
  }
}
  • 根据子文档对父文档进行排序

说明:根据子文档的字段影响父文档的的得分,而后父文档根据_score来排序。索引

下面例子中,父文档的得分为:_score * child_a1.salesCount,score_mode能够是min,max,sum,avg,first等。ip

GET /test_index_join/_search
{
  "query": {
    "has_child": {
      "type": "child_a1",
      "score_mode": "max", 
      "query": {
        "function_score": {
          "script_score": {
            "script": "_score * doc['salesCount'].value"
          }
        }
      }
    }
  },
  "sort": [
    {
      "_score": {
        "order": "asc"
      }
    }
  ]
}

 还能够依赖field_value_factor来影响父文档得分,效果类似,效率更高;functions支持多个field影响因子,多个因子的默认[score_mode]计分模式为multiply[相乘],还有其余可选模式为:min,max,avg,sum,first,multiply。开发

下面例子中,父文档的得分为:salesCount,由于没有其余的影响因子,若是有多个,则取最大的一个,由于score_mode为max。文档

GET /test_index_join/_search
{
  "query": {
    "has_child": {
      "type": "child_a1",
      "score_mode": "max", 
      "query": {
        "function_score": {
          "functions": [
            {
              "field_value_factor": {
                "field": "salesCount"
              }
            }
          ]
        }
      }
    }
  },
  "sort": [
    {
      "_score": {
        "order": "asc"
      }
    }
  ]
}

 

  • 根据父文档查询子文档
GET /test_index_join/_search
{
  "query": {
    "has_parent": {
      "parent_type": "parnet_a",
      # 基于parnet_a来搜索,query里的查询字段是parnet_a里的
      "query": {
        "range": {
          "price": {
            "gt": 1,
            "lte": 200
          }
        }
      }
    }
  }
}
相关文章
相关标签/搜索