首页 > 解决方案 > 如何在 Elasticsearch Python 客户端中查询包含撇号的字段

问题描述

我正在使用 Python 客户端使用 SQL 查询来查询 Elasticsearch 索引。我有一个包含城市名称的字段“City”,可以在字符串中包含撇号字符,例如“N'Djamena”。当我尝试查询此类字段时,我收到 Elasticsearch 解析错误。只想知道如何在 where 子句中使用这样的字符串。

我在我的 python 代码中使用下面的 SQL 查询

query = """select OverallIndex from topcities where Country = 'Chad' and City = 'N'Djamena' """

cityindex = es.sql.query(body={'query': query})

以下是我从 Elasticsearch 收到的异常消息

elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', "line 1:73: extraneous input 'Djamena' expecting {<EOF> , 'AND', 'BETWEEN', 'GROUP', 'HAVING', 'IN', 'IS', 'LIKE', 'LIMIT', 'NOT', 'OR', 'ORDER', 'RLIKE', LIMIT_ESC, '=', '<=>', NEQ, '<', ' <=', '>', '>=', '+', '-', '*', '/', '%', '::', STRING}")

我什至尝试从字段中替换撇号字符以及如下所示的 where 参数,但我仍然得到相同的异常

cityName = str("N'Djamena").replace("'","")

query = """select OverallIndex from topcities where Country = 'Chad' and replace(City,'*','') = '""" + cityName + """'"""

标签: pythonelasticsearchelasticsearch-dslelasticsearch-queryelasticsearch-dsl-py

解决方案


推荐阅读