原文地址:Elasticsearch 两个索引关联搜索_码农_菜猪的博客-CSDN博客_elasticsearch 关联查询
利用查询一个索引的值,并利用那个值去查询另外一个索引
1.Terms lookup query
要执行术语查找,请使用以下参数
index
(必需,字符串)从中获取字段值的索引的名称。
id
(必需,字符串)要从中获取字段值的文档的ID。
path
(必需,字符串)要从中获取字段值的字段名称。 Elasticsearch 使用这些值作为查询的搜索词。 如果字段值包含嵌套的内部对象的数组,则可以使用点表示法语法访问这些对象。
routing
(可选,字符串)从中获取术语值的文档的自定义路由值。 如果在为文档建立索引时提供了自定义路由值,则此参数是必需的。
1.1 创建 user_test 和 user_info_test索引
1.1.1 创建 user_test
POST user_test/_bulk
{ "create": {"_id":5}}
{ "username": "111","userId":"5"}
{ "create": {"_id":6}}
{ "username": "222" ,"userId":"6"}
{ "create": {"_id":7}}
{ "username": "333","userId":"7"}
{ "create": {"_id":8}}
{ "username": "4444","userId":"8"}
GET user_test/_search
{
"hits" : {
"total" : {
"value" : 4,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "user_test",
"_type" : "_doc",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"username" : "111",
"userId" : "5"
}
},
{
"_index" : "user_test",
"_type" : "_doc",
"_id" : "6",
"_score" : 1.0,
"_source" : {
"username" : "222",
"userId" : "6"
}
}
}
1.1.2 创建 user_info_test
POST user_info_test/_bulk
{ "create": {"_id":1}}
{ "name": "111","age":"15"}
{ "create": {"_id":2}}
{ "name": "222" ,"age":"16"}
{ "create": {"_id":3}}
{ "name": "333","age":"17"}
{ "create": {"_id":4}}
{ "name": "4444","age":"18"}
GET user_info_test/_search
{
"hits" : [
{
"_index" : "user_info_test",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "111",
"age" : "15"
}
},
{
"_index" : "user_info_test",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "222",
"age" : "16"
}
}
}
1.2 根据 user_test 关联搜索出user_info_test的数据
根据指定的id查询出user_test的username,在根据username查询出user_info_test关联的内容
GET user_info_test/_search
{
"query": {
"terms": {
"name": {
"index":"user_test",
"id":"5",
"path": "username"
}
}
}
}
此处的id为文档中的_id,暂时也只能是 _id,path 为返回字段