How to setup a custom Similarity class that depends on the current query string

Hi, hopefully someone can help me to sort out this question.

I have a custom lucene Similarity, it depends on a deep learning model that needs to analyze the current query string. In vanilla lucene that would be

Similarity similarity = new ABSimilarity("title", model, queryString)
 QueryParser parser = new ABQueryParser("title", new WhitespaceAnalyzer(), model);
Query query = parser.parse(queryString);


TopDocs hits =, 10);

In elasticsearch I have it declared as a new similarity

indexModule.addSimilarity("ABSIMILARITY", (settings, version, scriptService) -> createSimilarity(settings, version, scriptService))

I tried then update the similarity settings on query time in my query builder at

protected Query doToQuery(QueryShardContext context) {
PerFieldSimilarityWrapper similarity = (PerFieldSimilarityWrapper)context.getSearchSimilarity();

NonNegativeScoresSimilarity nnSimilarity = (NonNegativeScoresSimilarity)similarity.get(field);
ABSimilarity abSimilarity = (ABSimilarity)nnSimilarity.getDelegate();

the problem is that I see that the similarity is always the same instance while i need a new instance to safely support parallelism.

How could I create a new similarity on query time?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.