实现
源码中的conditionNode用到了二叉树的结构,表达不是很清楚,直接上个列子吧,好比我要查询的表达式为:git
name==yang and age==20
生成的conditionNode 的json结构为github
{ "op":"eq", "type":"normal", "left":{ "field":"name", "value":"yang", "op":"eq", "type":"normal" }, "right":{ "field":"age", "value":"20", "op":"eq", "type":"normal" }, "relation":"and" }
能够看到在最外层的conditionNode的左右两个节点封装单独的两个conditionNode ,且其关系为and,最后将 解析后的condition生成query dsl:web
{ "bool" : { "must" : [ { "bool" : { "must" : [ { "query_string" : { "query" : "name:\"yang\"" } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, { "bool" : { "must" : [ { "query_string" : { "query" : "age:\"20\"", } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }
若是只是支持顺序解析倒也没有什么特别的,这里举个添加括号提升查询条件优先级的列子:
expression : (name==yang and age>20) or (name == wang and age<=18)
解析后的conditionNode为:sql
{ "op":"eq", "type":"normal", "left":{ "op":"eq", "type":"normal", "left":{ "field":"name", "value":"yang", "op":"eq", "type":"normal" }, "right":{ "field":"age", "value":"20", "op":"gte", "type":"normal" }, "relation":"and" }, "right":{ "op":"eq", "type":"normal", "left":{ "field":"name", "value":"wang", "op":"eq", "type":"normal" }, "right":{ "field":"age", "value":"18", "op":"lte", "type":"normal" }, "relation":"and" }, "relation":"or" }
最后根据该conditionNode生成的dsl语句为:express
{ "bool" : { "should" : [ { "bool" : { "must" : [ { "bool" : { "must" : [ { "query_string" : { "query" : "name:\"wang\"" } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, { "bool" : { "must" : [ { "range" : { "age" : { "from" : null, "to" : "18", "include_lower" : true, "include_upper" : true, "boost" : 1.0 } } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, { "bool" : { "must" : [ { "bool" : { "must" : [ { "query_string" : { "query" : "name:\"yang\"" } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, { "bool" : { "must" : [ { "range" : { "age" : { "from" : "20", "to" : null, "include_lower" : false, "include_upper" : true, "boost" : 1.0 } } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }
冗余的东西有点多,你们将就着看吧,这里贴上源码地址