Q:非洲食人族的酋长吃什么?

elasticsearch怎么实现一个索引当中两个类型的关联查询呢?

Elasticsearch | 作者 zhbfy | 发布于2016年07月07日 | 阅读数:12979

例如有这样一个例子:
PUT /my_index/user/1
{
"name": "John Smith",
"email": "john@smith.com",
"dob": "1970/10/24"
"user": 1
}
PUT /my_index/blogpost/2
{
"title": "Relationships",
"body": "It's complicated...",
"user": 1
}
可不可以用一次查询查出 John的文档呢?
已邀请:

tangxingfu

赞同来自: medcl

使用嵌套查询或父子表,官方文档中有介绍

gfswsry - 80后IT

赞同来自: medcl

在查询的时候可以直接把types设置成user和blogpost......没有使用过,只是听人说过

szwx855 - Easy Simple

赞同来自: jonoexgf

es版本5.0.2
1、建设父子关系mapping ,父是用户表。子是博客表
curl -XPUT 'localhost:9200/my_index/_mapping?pretty' -d '
{
  "mappings":{
    "user":{     
       "name":{"type":"text","analyzer":"ik_max_word"},
       "email":{"type":"text","analyzer":"ik_max_word"},
       "dob":{"type":"date"}
   },
   "blogpost":{
     "properties":{
       "title":{"type":"text","analyzer":"ik_max_word"},
       "body":{"type":"text","analyzer":"ik_max_word"},
       "user":{"type":"long"}
      },
     "_parent":{
       "type":"user"
      }
    }
  }
}

2、插入用户数据
curl -XPOST 'localhost:9200/my_index/user/1?pretty' -d '
{
"name": "John Smith",
"email": "john@smith.com",
"dob": "1970/10/24"
"user": 1
}

3、插入用户ID为1的博客数据
curl -XPOST 'localhost:9200/my_index/blogpost/1000?parent=1pretty' -d '
{
"title": "Relationships",
"body": "It's complicated...",
"user": 1 
}

4、查询用户ID为1的所有博客。
curl -XPOST 'localhost:9200/my_index/blogpost/_search?pretty' -d '
{
  "query":{
   "has_parent":{
     "type":"user",
     "query":{
      "match":{"user":1}
     }
   }
  }
}

edison - 从事软件开发,热爱技术,个人博客:(程序员百味) http://www.bywei.cn

赞同来自:

 我也遇到了这样的问题,比你这问题还复杂的是,还需要进行排序。
以上列举:
query user all
order by count(blogpost.user)
 
 
期待大神有更好的解决办法

edison - 从事软件开发,热爱技术,个人博客:(程序员百味) http://www.bywei.cn

赞同来自:

medcl - 今晚打老虎。

赞同来自:

@zhbfy 问题不太清楚,是 name 包含 John 的文档还是 user 为1的?

sura0929

赞同来自:

你这个只能先查出name为john的user值,然后通过user来查询,get /my_index/_search {"query":{"match":{"user":1}}}

要回复问题请先登录注册