python - 在 python 请求中使用转义引号查询 Elasticsearch

标签 python elasticsearch python-requests

我正在尝试使用 python requests 查询 elasticsearch。正在关注this post ,我正在使用以下过程:

params = {
    "query": {
        "filtered": {
            "query": {
                "bool": {
                    "should": [
                        {
                            "query_string": {
                                "query": r'\"text in quotes\"'
                            }
                        }
                    ]
                }
            },
            "filter": {
                "bool": {
                    "must": [
                        {
                            "range": {
                                "@timestamp": {
                                    "from": 1458581389860,
                                    "to": 1458494989000
                                }
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 100,
}
response = requests.get(url, params=params)

不幸的是,查询中的引号似乎没有被 Elasticsearch 正确转义。我也尝试过:

  • '\\"引号内的文字\\"'
  • response = requests.get(url, data=json.dumps(params))

等效的curl 有效,如下所示:

curl -XGET 'MYURL/_search?pretty' -d '{
    "query": {
        "filtered": {
            "query": {
                "bool": {
                    "should": [
                        {
                            "query_string": {
                                "query": "\"test in quotes\""
                            }
                        }
                    ]
                }
            },
            "filter": {
                "bool": {
                    "must": [
                        {
                            "range": {
                                "@timestamp": {
                                    "from": 1458581389860,
                                    "to": 1458494989000
                                }
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 100,
}'

最佳答案

在 cURL 中,您正在转义引号。 "\"引号中的文本\"",这将成为“引号中的文本”

你的Python问题是,如果你使用单引号,就像你对r'\"text inquotes\"'所做的那样,你不需要转义任何东西,它将打印\“引号中的文本\”因为它是包含斜杠的原始字符串。

所以,你有两个选择:

  1. 对 Python 字符串使用双引号并转义 "\"引号中的文本\""
  2. 只需使用单引号和未转义的双引号'“引号中的文本”'

关于python - 在 python 请求中使用转义引号查询 Elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36138686/

相关文章:

performance - elasticsearch 计数有多快?

python - Scrapy - 连接以非干净的方式丢失。跨单个域不一致

Python、线程和请求 : What happens when I make concurrent requests in one session?

python - 动态时间扭曲中避免堆栈溢出的技术

python - 无法从异步函数内部生成并获取生成的数据

python - 裁剪功能 Jython JES

elasticsearch - 弹性索引/search_analyzer匹配所有 token

docker - 无法访问在 mac OS X 上运行在 docker 中的 elasticsearch

python - 使用 urllib2 获取纯文本,结果不完整

python - Django 中的 "slug"是什么?