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

**URL:** <https://discuss.elastic.co/t/how-to-setup-a-custom-similarity-class-that-depends-on-the-current-query-string/198504>\
**Category:** Elasticsearch\
**Created:** [September 7, 2019, 11:32am UTC](https://discuss.elastic.co/t/how-to-setup-a-custom-similarity-class-that-depends-on-the-current-query-string/198504 "2019-09-07T11:32:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![David\_G\_Ortega](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/david_g_ortega/32/46359_2.png) [@David\_G\_Ortega](https://discuss.elastic.co/u/David_G_Ortega)\
**Post date:** [September 7, 2019, 11:32am UTC](https://discuss.elastic.co/t/how-to-setup-a-custom-similarity-class-that-depends-on-the-current-query-string/198504/1 "2019-09-07T11:32:37Z")

</div>

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

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

searcher.setSimilarity(similarity);

TopDocs hits = searcher.search(query, 10);

```

In elasticsearch I have it declared as a new similarity

```auto
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

```auto
@Override
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?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [October 5, 2019, 11:32am UTC](https://discuss.elastic.co/t/how-to-setup-a-custom-similarity-class-that-depends-on-the-current-query-string/198504/2 "2019-10-05T11:32:38Z")

</div>

Closed on October 5, 2019, 11:32am UTC

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