4

I'm trying to create the simplest proxy possible in an API to execute searches on ElasticSearch nodes. The only reason for the proxy to be there is to "hide" the credentials and abstract ES from the API endpoint.

Using Nest.ElasticClient, is there a way to execute a raw string query? Example query that is valid in vanilla ES:

{
    "query": {
        "fuzzy": { "title": "potato" }
    }
}

In my API, I tried Deserializing the raw string into a SearchRequest, but it fails. I'm assuming it cannot deserialize the field:

var req = m_ElasticClient.Serializer.Deserialize<SearchRequest>(p_RequestBody);
var res = m_ElasticClient.Search<T>(req);
return m_ElasticClient.Serializer.SerializeToString(res);

System.InvalidCastException: Invalid cast from 'System.String' to 'Newtonsoft.Json.Linq.JObject'.

Is there a way to just forward the raw string query to ES and return the string response? I tried using the LowLevel.Search method without luck.

MicG
  • 85
  • 1
  • 5

2 Answers2

5

Yes, you can do this with NEST, check out the following

var searchResponse = client.Search<object>(s => s
        .Type("type").Query(q => q.Raw(@"{""match_all"":{}}")));

Hope that helps.

Rob
  • 9,664
  • 3
  • 41
  • 43
  • This works if the string is only the query part though, but what if I want the whole query descriptor including "size", "from" and "aggs" for example? – MicG May 22 '17 at 20:07
  • 1
    @MicG raw query only allows the query part and is intended for cases where new queries are introduced but the client does not have them yet, or where there may be bugs. If you'd like to send the whole search request json, check out the low level client: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/elasticsearch-net-getting-started.html Take a look at the search section in getting started guide for NEST for how to use both together: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/nest-getting-started.html#_searching_2 – Russ Cam May 22 '17 at 21:37
5

NEST does not support deserializing the short form of "field_name" : "your_value" of the Elasticsearch Query DSL, but it does support the long form "field_name" : { "value" : "your_value" }, so the following works

var client = new ElasticClient();

var json = @"{
    ""query"": {
        ""fuzzy"": { 
            ""title"": {
                ""value"": ""potato""
            }
        }
    }
}";

SearchRequest searchRequest;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
    searchRequest = client.Serializer.Deserialize<SearchRequest>(stream);
}

As Rob has answered, NEST also supports supplying a raw json string as a query

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266