Java SDK - Dynamic N1QL

Hello,

I’m new to Couchbase and I’m trying to write a N1QL query using the Java SDK, the problem is that I’m trying to build the query from a Map of fields and values in a dynamic way.
For example (I wanted to do this):

public Collection getMatching(Map<String, Object> conditions) {
Statement query = select(bucketName + “.*”).from(bucketName);

    for (Map.Entry<String, Object> condition : conditions.entrySet()) {
        query += query.where( i(condition.getKey()).eq(condition.getValue()) );
    }

    this.repository.getByN1ql(this.serverName, this.bucketName, query);

    [....] rest of method
}

But reading the API docs I can’t think of a way of doing this. I’ve already tried creating an object and passing it to where clause but it did not work as well.

Can anyone give me a way to implement this?

Hello,

i’ve managed to solve my problem. Here is the solution:

    Expression whereExpression = x("1").eq(1);

    for (Map.Entry<String, Object> condition : conditions.entrySet()) {

        whereExpression = whereExpression.and(i(condition.getKey()).eq(condition.getValue().toString()));

    }

    Statement query = select(bucketName + ".*").from(bucketName).where(whereExpression);

    N1qlQueryResult results = this.repository.getByN1ql(this.serverName, this.bucketName, query);
2 Likes