7

我有两个字符串类型的数组列表,一个是操作数,一个是运算符

ArrayList<String> operands = new ArrayList<String>();
ArrayList<String> operators = new ArrayList<String>();

他们像这样被填满

operands = { "\"symbol\": \"CHKP%\"", "\"price\": {$gt: 23.72\" };
operators = { "and"};

理想情况下,我会将其转换为像这样填充的单个 ArrayList

ArrayList<String> polishNotation = { "and", 
                   "\"symbol\": \"CHKP%\"", 
                   "\"price\": {$gt: 23.72\" };

为三个元素硬编码波兰表示法很容易,但我有不同数量的运算符和操作数(最多四个操作数和三个运算符)。此代码用于将 SQL 选择语句转换为 MongoDB.find() 语句。任何关于如何以波兰表示法(前缀波兰表示法)实现 ArrayList 合并的指针将不胜感激。

[编辑 2] 下面是一个带有 3 个运算符(“like”、“and”、“<”)和三个操作数('FLIR%'、“price”、“price”)的 SQL 语句示例,它与 MongoDB 等效。我认为使用波兰表示法可以帮助我将 SQL 的查询顺序转换为 Mongo 排序的查询

在 SQL 中

SELECT * FROM STOCK WHERE symbol like 'FLIR%' and price > 24.04 and price < 24.39;

在 MongoDB 中

db.STOCK.find({
    "symbol": "FLIR%",
    "price": {
        "$gt": 24.04,
        "$lt": 24.39
    }
}
4

1 回答 1

4

If you are going to write a parser like this it is going to a fairly big project because the sql query could get more and more complex. You could try using ANTLR. It has an sql grammar. Or GeneralSqlParser or other parser to tokenize your sql statement an then construct your mongo statements.

If you are not particular about writing a program you can rely on the Query Mongo project. It does what you need. Please refer to that site.

Still you are determined to get a quick solution for this via Java, you can try the below program. This uses jsoup to submit you query to the querymongo site and retrieve the mongo query.

Hope this helps :)

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class MongoQuery {

    public static void main(String[] args) throws Exception {

        System.setProperty("http.proxyHost", "10.9.248.37");
        System.setProperty("http.proxyPort", "18082");

        Document doc = Jsoup.connect("http://www.querymongo.com/")
                .data("MySQLQuery", "SELECT * FROM STOCK WHERE symbol like 'FLIR%' and price > 24.04 and price < 24.39")
                .post();

        for(Element e : doc.select("#mongoQuery")){
            System.out.println(e.val());
        }
    }
}
于 2014-05-14T14:48:04.783 回答