ElasticSearch关联查找并返回关联字段

inner_hits文档 : 链接地址

今天项目搜索引擎用到关联查找,Elasticsearch文档 里有has_parent方法,可是只能关联搜索当前type,不能返回被关联type的字段,于是各种google,Elasticsearch 提供了Inner Hits

这个参数,代码修改为:

curl -XGET  'http://localhost:9200/index/type/_search/?pretty=true' -d  '{
 "query": {
    "has_parent": {
      "type": "parent_type",
      "query": {
        "bool": {
          "must": [
            //此处为query查询的逻辑代码
          ]}
      },
      //注意此处添加inner_hits
       "inner_hits": {} 
    }
  }
}'

返回结果:

{
    "took": 6,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "index",
                "_type": "type",
                "_id": "1",
                "_score": 1,
                "_source": {
                    "id": "1",
                    "name": "搜索文档标题",
                    "content": "本篇内容的具体信息",
                    "user_id": "101662"
                },
                "inner_hits": {  //inner_hits返回了has_parent中匹配上的子文档
                    "parent_type": {
                        "hits": {
                            "total": 1,
                            "max_score": 1.592944,
                            "hits": [
                                {
                                    "_index": "index",
                                    "_type": "parent_type",
                                    "_id": "1",
                                    "_score": 1.592944,
                                    "_source": {
                                        "user_id": "101662",
                                        "user_name": "秦时明月"
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        ]
    }

}

此外,inner_hits支持返回部分字段信息,例如:

curl -XGET  'http://localhost:9200/index/type/_search/?pretty=true' -d  '{
 "query": {
    "has_parent": {
      "type": "parent_type",
      "query": {
        "bool": {
          "must": [
            //此处为query查询的逻辑代码
          ]}
      },
      //注意此处添加inner_hits
       "inner_hits": {
          "_source":["user_name"]
      } 
    }
  }
}'


0 评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注