弹性搜索DSL(Python)动态字段映射

2024-03-28 08:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在dict中存储了一些字段,如下所示:

 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
            ]
        }
    }
}

Tags: tosearchtypematchattributeredqueryattributes