首页 > 解决方案 > 弹性搜索 DSL (Python) 动态字段映射

问题描述

我有一些字段存储在字典中,如下所示:

 type_specific_attributes = {
     "color": "red",
     "fabric": "velvet",
     "material": "leather",
     "measurements": "1x2x3",
     "size": "Medium",
     "style": "Gucci"
}

我希望生成以下 ES 查询,其中该字典的键是动态映射的:

{
    "query": {
        "bool": {
            "should": [
                {
                    "match_phrase": {
                        "color": "red"
                    }
                },
                {
                    "match_phrase": {
                        "fabric": "velvet"
                    }
                },
                ... // and so forth for all the keys in my dictionary
            ]
        }
    }
}

我尝试将所有查询添加到列表并将该列表传递给 .query() 函数:

# Append all Queries to a list
should = []
for attribute in type_specific_attributes:
    should.append(Q("match_phrase", attribute=type_specific_attributes[attribute]))

# Create an instance of the Search object
s = Search(using=self.client, index=self.index)

# Add Query to Search Object
s = s.query(
        Q(
            "bool",
            should=should
        )
    )

但生成的查询没有动态字段:

{
    "query": {
        "bool": {
            "should": [
                {
                    "match_phrase": {
                        "attribute": "red"  // I'm expecting this to be dynamic, not "attribute"
                    }
                },
                ... // a bunch of other same objects
            ]
        }
    }
}

标签: pythonelasticsearchsearchdsl

解决方案


推荐阅读