如何将中缀表达式转换为 Elasticsearch 查询
我的接线员是 ! + *
并且用户可以使用这些运算符进行任何表达,例如:
(((A*B*(!C))*(D*E))+F)*G
我希望将其转换为 bool query在 Elasticsearch 中
编辑
我不知道我为什么不早点说这个,但我已经写了一段代码将中缀表达式转换为后缀表达式,然后我调用了一个非常肮脏的递归方法来创建 should (+), must (*) and must_not (!)
但我正在寻找的是一种优化的方式来为我做这个把戏。
我最后的查询是这样的,我认为这是非常非常讨厌的:
{
"from": 0,
"size": 10,
"_source": [
"*"
],
"index": "insta_userpost_new2",
"body": {
"query": {
"bool": {
"must": [
{
"match_phrase": {
"caption.text": "G"
}
},
{
"bool": {
"should": [
{
"match_phrase": {
"caption.text": "F"
}
},
{
"bool": {
"must": [
{
"bool": {
"must": [
{
"match_phrase": {
"caption.text": "E"
}
},
{
"match_phrase": {
"caption.text": "D"
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"must_not": [
{
"match_phrase": {
"caption.text": "C"
}
},
{
"bool": {
"must": [
{
"match_phrase": {
"caption.text": "B"
}
},
{
"match_phrase": {
"caption.text": "A"
}
}
]
}
}
]
}
}
]
}
}
]
}
}
]
}
}
]
}
}
}
}
最佳答案
我可能会尝试利用 simply_query_string
.为此,您必须:
- 将
+
替换为|
(对于OR
) - 然后将
*
替换为+
(对于AND
) - 最后将
!
替换为-
(对于NOT
)
所以如果用户输入这个:
(((A*B*(!C))*(D*E))+F)*G
你会得到这个
(((A+B+(-C))+(D+E))|F)+G
这是一个 bool 表达式,您可以直接在 simply_query_string
查询中使用。
GET /_search
{
"query": {
"simple_query_string" : {
"fields" : ["content"],
"query" : "(((A+B+(-C))+(D+E))|F)+G"
}
}
}
关于php - 将中缀表达式转换为 Elasticsearch 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985156/