0

I have a microservice I am designing for getting "Book" information, and one of the capabilities is to query Solr and fuse it with some DB results that I queried.

I am looking for, what I am calling a "query maker pattern" something that will generate dynamic solr queries. The idea in my head was a class like

public class Query {
    public Attribute[]; 
}

public class Attribute {
    public String type; 
    public String value;
}

But I'm not sure what the best way to generate dynamic queries in an object oriented way. There is a bad way of having a bunch of functions that append strings like:

public function String addSort(String value, Boolean isAscending){
    return value + "+" + (isAscending ? "asc" : "desc");
}
public function String addFacet(String facetName){
    etc etc
}

It would be best to have something like a toString() function for the Query object, and then using that as a the request to Solr?

2
  • A URI is made up of a "path" and a "query". Both of them have syntax and must be composed using uri-encoding rules. You could create a domain-specific-language (DSL) on top of those bases that gives you what you want. – BobDalgleish Dec 18 '19 at 22:33
  • 1
    You'd be better just using a library for Solr for whichever language you're coding in. – Chris Murray Dec 19 '19 at 11:53
0

I believe the pattern you are looking for is the Builder Pattern


It should look something like this:

public class Query {
    public Attribute[]; 

    public Query(string suffix) {
        // ...
    }

}

public class QueryBuilder {

    string suffix;

    public QueryBuilder() {
        this.suffix = "";
    } 

    public QueryBuilder WithFacet() {
        // etc etc
        return this;
    }

    public QueryBuilder WithSort(bool isAscending) {
        suffix += "+" + (isAscending ? "asc" : "desc");
        return this;
    }

    public Query Build() {
        return new Query(this.suffix);
    }

}

Usage:

Query myQuery = QueryBuilder.WithFacet().WithSort(true).Build();


Depending on the language you are programming you can even add some syntactic sugar:

public static class A
{
    public QueryBuilder Query => new QueryBuilder();
}
public class QueryBuilder {

    // ...
    public implicit operator Query(QueryBuilder builder) => builder.Build();
}

Usage:

Query myQuery = A.Query.WithFacet().WithSort(true);

0

To build a query, you can build an expression tree then compile that into the domain-specific language.

C# does this extensively, for example it allows you to construct an IQueryable in memory and linq-to-sql will translate it into SQL.

Apparently, there is a linq-to-solr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.