Search code examples
spring-bootkotlinelasticsearchelasticsearch-java-api

Writing a script score search using elastic search Java API


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


Solution

  • 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()