0

I have a C# API that uses the Elastic NEST SDK. My version of Elastic is v8.4 It takes an Elastic search query as a JSON request.

im trying to create the NEST request object SearchRequest<T> using this JSON request and the index name.

This is my helper method that tries to deserialize the JSON request to a QueryContainer however it always returns in a null QueryContainer resulting in a search with no query.

public static SearchRequest<T> GetSearchRequestFromJson<T>(string json, string indexName) where T : class
{
    var request = new SearchRequest<T>(indexName);
    request.Query = JsonConvert.DeserializeObject<QueryContainer>(json);
    return request;
}

looking at other examples they are manually mapping the JSON request, but the request is dynamic so I want to avoid if possible any manual object instantiation based on the JSON request

what is the best practise for this? do I need to refactor and use the low level client to support JSON requests?

JGilmartin
  • 8,683
  • 14
  • 66
  • 85
  • NEST deserialization supports only the longer form of the query IIRC. I understand your query json is dynamic, but are you sure you're always getting the longer form of queries to begin with? – Sai Gummaluri Jun 16 '23 at 06:47

1 Answers1

-1

Instead of directly deserializing the JSON request into a QueryContainer object, you can use the NEST's low-level capabilities to handle the dynamic JSON request. This approach allows you to work with raw JSON without the need for manual object instantiation.

Here's an example of how you can modify your helper method to use the low-level client:

{
var request = new SearchRequest<T>(indexName);
request.RawQuery = new RawJson(json);
return request;

}

In this modified method, instead of deserializing the JSON into a QueryContainer, we assign the raw JSON request to the RawQuery property of the SearchRequest object using the RawJson class from NEST. This way, the JSON query will be sent as-is to ElasticSearch without any additional mapping or deserialization.

By using the RawQuery property, you can handle dynamic JSON requests without the need for manual object instantiation or mapping. This approach leverages the low-level client capabilities of NEST and allows you to work with the raw JSON query directly.

Remember to properly configure and initialize your NEST client with the appropriate ElasticSearch version to ensure compatibility.