Elasticsearch:将 SQL 转换为 DSL


#Elasticsearch 笔记


使用 Golang 转换

$ go get -u github.com/cch123/elasticsql
$ go get -u github.com/tidwall/pretty

代码示例:

package main

import (
    "fmt"
    "github.com/cch123/elasticsql"
    "github.com/tidwall/pretty"
)

var sql = `
select * from user_info
where id=1
`

func main() {
    dsl, esType, _ := elasticsql.Convert(sql)
    // 打印 type 名称
	fmt.Println(esType)
	fmt.Println()
    // 打印 dsl
    fmt.Println(dsl)
    fmt.Println()
    // 打印格式化后的 dsl
	var result = pretty.Pretty([]byte(dsl))
	fmt.Println(string(result))
}

运行结果:

user_info

{"query" : {"bool" : {"must" : [{"match_phrase" : {"id" : {"query" : "1"}}}]}},"from" : 0,"size" : 1}

{
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "id": {
              "query": "1"
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 1
}


( 本文完 )