gpt4 book ai didi

sql - 像自定义 dsl 查询一样将 Sql 转换为 ElasticSearch?

转载 作者:行者123 更新时间:2023-12-02 22:09:39 28 4
gpt4 key购买 nike

我们正在使用 antlr4 构建我们自己的类似于 Mysql 的查询语言。除了我们只使用 where clause ,换句话说,用户没有输入 select/from声明。

我能够为它创建语法并在 golang 中生成词法分析器/解析器/监听器。

在我们的语法文件 EsDslQuery.g4 下面:

grammar EsDslQuery;

options {
language = Go;
}

query
: leftBracket = '(' query rightBracket = ')' #bracketExp
| leftQuery=query op=OR rightQuery=query #orLogicalExp
| leftQuery=query op=AND rightQuery=query #andLogicalExp
| propertyName=attrPath op=COMPARISON_OPERATOR propertyValue=attrValue #compareExp
;

attrPath
: ATTRNAME ('.' attrPath)?
;

fragment ATTR_NAME_CHAR
: '-' | '_' | ':' | DIGIT | ALPHA
;

fragment DIGIT
: ('0'..'9')
;

fragment ALPHA
: ( 'A'..'Z' | 'a'..'z' )
;

attrValue
: BOOLEAN #boolean
| NULL #null
| STRING #string
| DOUBLE #double
| '-'? INT EXP? #long
;

...

查询示例: color="red" and price=20000 or model="hyundai" and (seats=4 or year=2001)
ElasticSearch 通过插件支持 sql 查询: https://github.com/elastic/elasticsearch/tree/master/x-pack/plugin/sql .

很难理解java代码。

由于我们有逻辑运算符,我不太确定如何获取解析树并将其转换为 ES 查询。有人可以帮助/建议想法吗?

更新 1:添加了更多带有相应 ES 查询的示例

查询示例 1: color="red" AND price=2000
ES查询1:
{
"query": {
"bool": {
"must": [
{
"terms": {
"color": [
"red"
]
}
},
{
"terms": {
"price": [
2000
]
}
}
]
}
},
"size": 100
}


查询示例 2: color="red" AND price=2000 AND (model="hyundai" OR model="bmw")
ES查询2:
{
"query": {
"bool": {
"must": [
{
"bool": {
"must": {
"terms": {
"color": ["red"]
}
}
}
},
{
"bool": {
"must": {
"terms": {
"price": [2000]
}
}
}
},
{
"bool": {
"should": [
{
"term": {
"model": "hyundai"
}
},
{
"term": {
"region": "bmw"
}
}
]
}
}
]
}
},
"size": 100
}



查询示例 3: color="red" OR color="blue"
ES 查询 3:
{
"query": {
"bool": {
"should": [
{
"bool": {
"must": {
"terms": {
"color": ["red"]
}
}
}
},
{
"bool": {
"must": {
"terms": {
"color": ["blue"]
}
}
}
}
]
}
},
"size": 100
}

最佳答案

工作演示网址:https://github.com/omurbekjk/convert-dsl-to-es-query-with-antlr , 估计花费时间: ~3 周

在研究了 antlr4 和几个例子后,我发现了一个简单的解决方案,包括监听器和堆栈。类似于使用堆栈计算表达式的方式。

我们需要用我们的覆盖默认基本监听器来获取每个进入/退出语法规则的触发器。重要的规则是:

  • 比较表达式(价格=200,价格>190)
  • 逻辑运算符(OR、AND)
  • 括号(为了正确构建 es 查询,我们需要编写正确的语法文件并记住运算符的优先级,这就是为什么括号在语法文件中的首位)

  • 在我用 golang 编写的自定义监听器代码下方:
    package parser

    import (
    "github.com/olivere/elastic"
    "strings"
    )

    type MyDslQueryListener struct {
    *BaseDslQueryListener
    Stack []*elastic.BoolQuery
    }

    func (ql *MyDslQueryListener) ExitCompareExp(c *CompareExpContext) {
    boolQuery := elastic.NewBoolQuery()

    attrName := c.GetPropertyName().GetText()
    attrValue := strings.Trim(c.GetPropertyValue().GetText(), `\"`)
    // Based on operator type we build different queries, default is terms query(=)
    termsQuery := elastic.NewTermQuery(attrName, attrValue)
    boolQuery.Must(termsQuery)
    ql.Stack = append(ql.Stack, boolQuery)
    }

    func (ql *MyDslQueryListener) ExitAndLogicalExp(c *AndLogicalExpContext) {
    size := len(ql.Stack)
    right := ql.Stack[size-1]
    left := ql.Stack[size-2]
    ql.Stack = ql.Stack[:size-2] // Pop last two elements
    boolQuery := elastic.NewBoolQuery()
    boolQuery.Must(right)
    boolQuery.Must(left)
    ql.Stack = append(ql.Stack, boolQuery)
    }

    func (ql *MyDslQueryListener) ExitOrLogicalExp(c *OrLogicalExpContext) {
    size := len(ql.Stack)
    right := ql.Stack[size-1]
    left := ql.Stack[size-2]
    ql.Stack = ql.Stack[:size-2] // Pop last two elements
    boolQuery := elastic.NewBoolQuery()
    boolQuery.Should(right)
    boolQuery.Should(left)
    ql.Stack = append(ql.Stack, boolQuery)
    }


    和主文件:
    package main

    import (
    "encoding/json"
    "fmt"
    "github.com/antlr/antlr4/runtime/Go/antlr"
    "github.com/omurbekjk/convert-dsl-to-es-query-with-antlr/parser"
    )

    func main() {
    fmt.Println("Starting here")
    query := "price=2000 OR model=\"hyundai\" AND (color=\"red\" OR color=\"blue\")"
    stream := antlr.NewInputStream(query)
    lexer := parser.NewDslQueryLexer(stream)
    tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
    dslParser := parser.NewDslQueryParser(tokenStream)
    tree := dslParser.Start()

    listener := &parser.MyDslQueryListener{}
    antlr.ParseTreeWalkerDefault.Walk(listener, tree)

    esQuery := listener.Stack[0]

    src, err := esQuery.Source()
    if err != nil {
    panic(err)
    }
    data, err := json.MarshalIndent(src, "", " ")
    if err != nil {
    panic(err)
    }

    stringEsQuery := string(data)
    fmt.Println(stringEsQuery)
    }

    /** Generated es query
    {
    "bool": {
    "should": [
    {
    "bool": {
    "must": [
    {
    "bool": {
    "should": [
    {
    "bool": {
    "must": {
    "term": {
    "color": "blue"
    }
    }
    }
    },
    {
    "bool": {
    "must": {
    "term": {
    "color": "red"
    }
    }
    }
    }
    ]
    }
    },
    {
    "bool": {
    "must": {
    "term": {
    "model": "hyundai"
    }
    }
    }
    }
    ]
    }
    },
    {
    "bool": {
    "must": {
    "term": {
    "price": "2000"
    }
    }
    }
    }
    ]
    }
    }

    */

    关于sql - 像自定义 dsl 查询一样将 Sql 转换为 ElasticSearch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60280326/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com