首页 > 解决方案 > elasticsearch + python在字符串数组中搜索子字符串

问题描述

我在弹性搜索中有 10k+ 条记录。其中一个字段(部门)以数组的形式保存数据

例如记录是

{
        "username": "tom",
        "dept": [
            "cust_service",
            "sales_rpr",
            "store_in",
        ],
        "location": "NY"
}



{
        "username": "adam",
        "dept": [
            "cust_opr",
            "floor_in",
            "mg_cust_opr",
        ],
        "location": "MA"
}
.
.
.

我想在dept字段上进行自动完成,如果用户搜索cus它应该返回

["cust_service", "cust_opr", "mg_cust_opr"]

最佳匹配在顶部

我已查询

query = {
            "_source": [],
            "size": 0,
            "min_score": 0.5,
            "query": {
                "bool": {
                    "must": [
                        {
                            "wildcard": {
                                "dept": {
                                    "value": "*cus*"
                                }
                            }
                        }
                    ],
                    "filter": [],
                    "should": [],
                    "must_not": []
                }
            },
            "aggs": {
                "auto_complete": {
                    "terms": {
                        "field": f"dept.raw",
                        "size": 20,
                        "order": {"max_score": 'desc'}
                    },
                    "aggs": {
                        "max_score": {
                            "avg": {"script": "_score"}
                        }
                    }
                }
            }
        }

它没有给出 ["cust_service", "cust_opr", "mg_cust_opr"]而是给出与搜索键(cus)无关的其他答案。但是当字段只是string而不是array它时,它会按预期给出结果。

我该如何解决这个问题?

提前致谢!

标签: pythonelasticsearch

解决方案


推荐阅读