0

I have the following query to use with Elasticsearch.

{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "script_score": {
        "script": {
          "source": "cosineSimilarity(params.query_vector, 'vector') + 1",
          "params": {
            "query_vector": [/* Your query vector here */]
          }
        }
      }
    }
  }
}

I am trying to convert this query into kotlin with the new Java API. Unfortunately, I am unable to find documentation on how to convert this query. I have tried multiple ways but to no avail.

I have tried the following from chatGPT but am unable to get it to work.

fun main() {
    val queryVector = /* Your query vector here */

    val scriptScoreFunction = ScriptScoreFunction(
        Script("painless", "cosineSimilarity(params.query_vector, 'vector') + 1"),
        mapOf("query_vector" to queryVector)
    )
    
    val functionScoreQuery = FunctionScoreQuery(
        MatchAllQuery(),
        listOf(ScriptScoreFunctionBuilder(scriptScoreFunction))
    ).scoreMode(ScoreMode.SUM)
    
    val searchRequest = SearchRequest(Index("_all")).apply {
        source(SearchSourceBuilder().apply {
            query(functionScoreQuery)
        })
    }
    
    println(searchRequest.source().toString())

}

Most resources are also using the older elasticsearch library but I have to use co.elastic.clients library which is the latest api for java

1 Answer 1

2

After a bit of trial and error, I have figured out that with the latest Java Elasticsearch API , the code would look as follows:

val scriptBuidler = ScriptBuilders.inline()
    .source(cosineSimilarity(params.query_vector, 'vector') + 1)
    .params("queryVector", Jsondata.of("[1.0, 2.0]"))
    .build()

SearchRequest.Builder()
    .index("name_of_index")
    .size(3)
    .minscore(0.01)
    .query(
        ScriptScoreQuery.Builder()
        .query(hshs)
        .script(
            ScriptBuilder().inline(scriptBuilder).build()
        )
        .build()
        ._toQuery()
    )
    .source(
        SourceConfig.Builder().build()
    )
    .build()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.