實現
源碼中的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 } }
冗餘的東西有點多,你們將就着看吧,這裏貼上源碼地址