Escaping special characters in elasticsearch(在elasticsearch中转义特殊字符)
问题描述
我正在使用 elasticsearch python 客户端 对 elasticsearch 实例进行一些查询我们正在托管.
I am using the elasticsearch python client to make some queries to the elasticsearch instance that we are hosting.
我注意到有些字符需要转义.具体来说,这些...
I noticed that some characters need to be escaped. Specifically, these...
+ - && || ! ( ) { } [ ] ^ " ~ * ? :
除了我已经想到的之外,有没有一种干净的方法可以做到这一点?当然有比做更清洁的方法
Is there a clean way to do this beyond what I've already got in mind? Surely there is a cleaner way than doing
term
.replace("+", "+")
.replace("-", "-")
# ....etc
我希望有一个我可以使用的 API 调用,但我在文档中找不到.这似乎是一个很常见的问题,应该由某人解决.
I was hoping there was an API call that I could use, but I can't find one in the docs. This seems like a common enough issue that it should have been solved by someone.
有人知道正确"的做法吗?
Does anyone know the "correct" way of doing this?
我仍然不确定是否有 API 调用,但我得到的东西足够简洁,足以让我满意.
EDIT : I am still not sure if there is an API call, but I got things concise enough to where I am happy.
def needs_escaping(character):
escape_chars = {
'\' : True, '+' : True, '-' : True, '!' : True,
'(' : True, ')' : True, ':' : True, '^' : True,
'[' : True, ']': True, '"' : True, '{' : True,
'}' : True, '~' : True, '*' : True, '?' : True,
'|' : True, '&' : True, '/' : True
}
return escape_chars.get(character, False)
sanitized = ''
for character in query:
if needs_escaping(character):
sanitized += '\%s' % character
else:
sanitized += character
推荐答案
是的,您需要在 query_string 查询.为此(假设您使用的是 PyLucene),您应该能够使用 QueryParserBase.escape(String)
.
Yes, those characters will need to be replaced within content you want to search in a query_string query. To do that (assuming you are using PyLucene), you should be able to use QueryParserBase.escape(String)
.
除此之外,您始终可以根据您的需要调整 QueryParserBase.escape
源代码:
Barring that, you could always adapt the QueryParserBase.escape
source code to your needs:
public static String escape(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// These characters are part of the query syntax and must be escaped
if (c == '\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
|| c == '^' || c == '[' || c == ']' || c == '"' || c == '{' || c == '}' || c == '~'
|| c == '*' || c == '?' || c == '|' || c == '&' || c == '/') {
sb.append('\');
}
sb.append(c);
}
return sb.toString();
}
这篇关于在elasticsearch中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在elasticsearch中转义特殊字符
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01