How to Pass a Static or Query Value to the Response in OpenSearch

I appreciate your help in advance,

I’m trying to pass a static value or a query-specific identifier (e.g., ‘query_id’) from my search query to the response in OpenSearch. This value is not stored in the index, and I want it to be included in the search results for tracking purposes,

In a high level I store my queries in a PostgreSQL database then I read them, loop through each, build open search query and then execute multi search, when I get the response I have to merge that with some other datasets, hence I want to know which response is belong to which query, so my goal is to find a way to pass query ID in search query and retrieve it in the response

For example in the below multi search query I somehow want to add the query id for each query and then see the ID in the response, maybe in the response header
{
“query”: {
“match” : {
“job” : “engineer”
}
“query”: {
“match” : {
“job” : “sales”
}
}
}

named queries might be an answer

Hi @salimy,

If I got your question correctly, you could use something like the following:

GET index/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "query_id": {
      "script": {
        "source": "'your-staticValue'"
      }
    }
  }
}

i.e.:

Best,
mj

Thank you very much for your response, It is a great solution however there is a caveat; if the hit array does not have any row it does not show the “matched_queries”, based on my requirements query with no data is N/A so I still have to track the static value for a query that does not have anything on the response.

Great to know about the “Named Queires”, let me know if you can think of any work around for that.

Thank you very much for your response, I was trying this earlier, however I get error if I exactly run the syntax you posted,


{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "cannot execute scripts using [field] context"
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "test_index",
        "node": "V_l0TzpWTk2p4gug-lF1zA",
        "reason": {
          "type": "illegal_argument_exception",
          "reason": "cannot execute scripts using [field] context"
        }
      }
    ],
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "cannot execute scripts using [field] context",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "cannot execute scripts using [field] context"
      }
    }
  },
  "status": 400
}