首页 > 解决方案 > 无法在弹性中获取连接查询

问题描述

我得到了 elasticsearch 7.3 版和两个索引,profilespurchases是它们的映射:

\purchases
{
    "purchases": {
        "mappings": {
            "properties": {
                "product": {
                    "type": "keyword"
                },
                "profile": {
                    "type": "join",
                    "eager_global_ordinals": true,
                    "relations": {
                        "profiles": "purchases"
                    }
                }
            }
        }
    }
}

\profiles
{
    "profiles": {
        "mappings": {
            "properties": {
                "user": {
                    "type": "keyword"
                }
            }
        }
    }
}

我以这种方式添加了一个配置文件user:abc, _id:1和两次购买

{
    "profile": {"name": "profiles", "parent": "1"},
    "product" : "tomato",
}
{
    "profile": {"name": "profiles", "parent": "1"},
    "product" : "tomato 2",
}

然后我搜索查询购买

{
    "query": {
    "has_parent": {
      "parent_type": "profiles",
      "query": {
        "query_string": {
          "query": "user:abc"
        }
      }
    }
  }
}

我得到空结果,怎么了?

标签: elasticsearch

解决方案


如Join 数据类型的文档中所述,您不能在多个索引上创建父子关系:

连接数据类型是一个特殊字段,它在相同索引的文档中创建父/子关系。

如果您想使用连接数据类型,则必须在一个索引中对其进行建模。

更新

这就是您的映射和文档索引的样子:

PUT profiles-purchases-index
{
  "mappings": {
    "properties": {
      "user":{
        "type": "keyword"
      },
      "product":{
        "type": "keyword"
      },
      "profile":{
        "type": "join",
        "relations":{
          "profiles": "purchases"
        }
      }
    }
  }
}

索引父文档:

PUT profiles-purchases-index/_doc/1
{
  "user": "abc",
  "profile": "profiles"
}

索引子文档:

PUT profiles-purchases-index/_doc/2?routing=1
{
  "product": "tomato",
  "profile":{
    "name": "purchases",
    "parent": 1
  }
}

PUT profiles-purchases-index/_doc/3?routing=1
{
  "product": "tomato 2",
  "profile":{
    "name": "purchases",
    "parent": 1
  }
}

运行查询:

GET profiles-purchases-index/_search
{
  "query": {
    "has_parent": {
      "parent_type": "profiles",
      "query": {
        "match": {
          "user": "abc"
        }
      }
    }
  }
}

回复:

{
  ...
    "hits" : [
      {
        "_index" : "profiles-purchases-index",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_routing" : "1",
        "_source" : {
          "product" : "tomato",
          "profile" : {
            "name" : "purchases",
            "parent" : 1
          }
        }
      },
      {
        "_index" : "profiles-purchases-index",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_routing" : "1",
        "_source" : {
          "product" : "tomato 2",
          "profile" : {
            "name" : "purchases",
            "parent" : 1
          }
        }
      }
    ]
  }
}

请注意,您必须设置路由参数来索引子文档。但请参阅文档。


推荐阅读