需求:将sql语句转为es查询所用的json语句

github源码地址:

https://gitee.com/weiyxiong_admin/elasticsearch-sql/blob/master/src/test/java/org/nlpcn/es4sql/ExplainTest.java

比如将select * from esIndex where lastTime = 1648540192929
转化为es查询语句
{"from":0,"size":1000,"query":{"bool":{"filter":[{"bool":{"must":[{"match_phrase":{"lastTime ":{"query":1648540192929,"slop":0,"zero_terms_query":"NONE","boost":1.0}}}],"adjust_pure_negative":true,"boost":1.0}}],"adjust_pure_negative":true,"boost":1.0}}}

1、添加pom.xml依赖

<!-- https://mvnrepository.com/artifact/org.nlpcn/elasticsearch-sql -->
		<dependency>
    		<groupId>org.nlpcn</groupId>
    		<artifactId>elasticsearch-sql</artifactId>
    		<version>6.8.13.0</version>
		</dependency>

2、scala 将sql转为es查询json语句

 
object ESUtils {
// 1、获取searchDao
lazy val searchDao = {
		import org.elasticsearch.client.Client
		import org.elasticsearch.client.node.NodeClient
		import org.elasticsearch.common.settings.Settings
		import org.elasticsearch.common.util.concurrent.ThreadContext
		import org.elasticsearch.threadpool.ThreadPool
		// 填写上自己的cluster.name
        val settings = Settings.builder().put("cluster.name", MetaStorageImplementation.elasticsearchClusterName).build()
        // val settings = Settings.builder().put("cluster.name", "my-application").build()
        val  threadPool = new ThreadPool(settings)
		val client = new NodeClient(settings, threadPool)
		new org.nlpcn.es4sql.SearchDao(client) 
	}
//2、通过sql转为es查询语句
	def sqlToEsQuery(sql : String) : String = {
		val string = searchDao.explain(sql).explain().explain()
		string
	}

3、测试

def main(args: Array[String]): Unit = {
	val sql = ESUtils.sqlToEsQuery("select * from esIndex where lastTime = 1648540192929")
	val esJSON =ESUtils.sqlToEsQuery(sql)
    println(esJSON)
   }
}

4、查询返回结果展示(即步骤三esJSON结果打印)

{"from":0,"size":1000,"query":{"bool":{"filter":[{"bool":{"must":[{"match_phrase":{"lastAccessed":{"query":1648540192929,"slop":0,"zero_terms_query":"NONE","boost":1.0}}}],"adjust_pure_negative":true,"boost":1.0}}],"adjust_pure_negative":true,"boost":1.0}}}

5、打开postman

POST请求
请求头: http://ip:port/esIndex /_search
请求体:
为 步骤四的返回结果展示esJSON
{"from":0,"size":1000,"query":{"bool":{"filter":[{"bool":{"must":[{"match_phrase":{"lastTime":{"query":1648540192929,"slop":0,"zero_terms_query":"NONE","boost":1.0}}}],"adjust_pure_negative":true,"boost":1.0}}],"adjust_pure_negative":true,"boost":1.0}}}
查询,即可查到符合条件的数据
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐