Implementing free form query language in Java

两盒软妹~` 提交于 2019-12-11 21:09:10

问题


I am working on an api which will take a search string like "(A < 5) & (B = xyz*)" and respond with the correct result. This custom query language is predefined and I can't change it. I know that I can specify the CFG for this expression and then use ANTRL to construct the parse tree and implement this feature. Is there an easier and efficient way to do this in Java? Is there any library that can handle this kind of generic query language?


回答1:


Parsers generated by Antlr are very efficient. They are not trivial to write, but I can't think of any alternatives that are significantly easier.

Is there any library that can handle this kind of generic query language?

The problem is that there is no such thing as a generic query language. Each one is different, and yours is no exception ... by the looks of it.

If this is just an expression language, and you just want to "parse and evaluate" them, I suggest that you use Antlr, but don't construct a parse tree. Instead, embed the evaluation code in the grammar itself, and have each production deliver the result of evaluating the subexpression that it matches. (I bet there's an example that does this in a tutorial ...)




回答2:


You can either generate java class on the fly or use one of available scripting languages, e.g. JavaScript that is a part of JDK. Just create valid JavaScript statement and evaluate it.

Other available languages are Groovy, Jython etc. But their usage requires external dependencies. I think that your choice should be driven by other requirement. If you share them with the community you can probably get more concrete recommendations.



来源:https://stackoverflow.com/questions/16459115/implementing-free-form-query-language-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!