Querying dense_vector from the High Level REST Java API

All the examples I can find for querying dense vector mention script queries, eg. Searching with Dense Vector
However, I have no idea on how to use those with the HL API.
Is this possible at all and if yes then can you ES wizards give an example?

You can use QueryBuilders.scriptScoreQuery() and create a script score query with that and then execute a search? is that what you are after?

1 Like

That's it, however I would appreciate an example on how to translate the example vector query from the docs to the Java HL REST API. I haven't been able to find one for Java, although there are examples for other languages.

{
  "size" : 5,
  "query": {
    "script_score": {
      "query" : {
        "match_all" : {}
      },
      "script": {
        "source": "cosineSimilarity(params.queryVector, title_vector) + 1.0",
        "params": {
          "title_vector": [1,2,3]
        }
      }
    }
  }
}

Update
trying the approach shown here although I'd prefer to use just the Java API https://discuss.elastic.co/t/cannot-set-up-script-score-for-dense-vector-using-java-rest-api/238849/3. This gets executed but all scores are 1.0 - only the match_all query gets executed. What I'm doing wrong?

  SearchTemplateRequest request = new SearchTemplateRequest();
    request.setRequest(searchRequest);
    request.setScriptType(ScriptType.INLINE);


    def script =
            "{ \"query\":   " +
                    "{" +
                    "    \"script_score\": {       " +
                    "        \"query\": { " +
                    "           \"query_string\" : { " +
                    "               \"query\" : \"" + "match_all" + "\", " +
                    "                : \"{}\" " +
                    "            }  " +
                    "        },   " +
                    "        \"script\": { " +
                    "            \"source\": \"cosineSimilarity( " + vectors+ ",'title_vector') + 1.0\"  " +
                    "        } " +
                    "    }  " +
                    "}" +
                    "}  ";
    request.setScript(script);
    SearchResponse s = elastic.search(request.getRequest(), RequestOptions.DEFAULT)

Duh - there is an searchTemplate option. Using it however gives error
[search_template] params doesn't support values of type: VALUE_NULL"}],"type":"x_content_parse_exception",

The error persists even if I add script params in the request and it's barely mentioned on the web - what's happening?

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