Kamlesh Joshi
Kamlesh Joshi

Reputation: 21

InMemoryConnection Elasticsearch jsonSerializationException in nest version 6.x

With NEST version 6.x and NEST.JSonSerializer version 6.x, I am getting JSONSerialization exception, with inMemory elasticsearch for unit test.

I tried with Nest and JsonSersializer versions 7.x, and it was working fine. But my production server has 6.x versions, so I need to run the test on 6.x NEST Client.

    var response = new
    {
        took = 1,
        timed_out = false,
        _shards = new
            {
                total = 2,
                successful = 2,
                failed = 0
            },
                hits = new
                {
                    total = new { value = 25 },
                    max_score = 1.0,
                    hits = Enumerable.Range(1, 25).Select(i => (object)new
                    {
                        _index = "project",
                        _type = "project",
                        _id = $"Project {i}",
                        _score = 1.0,
                        _source = new { name = $"Project {i}" }
                    }).ToArray()
                    }
     };

    var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
    var connection = new InMemoryConnection(responseBytes, 200);
    var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var settings = new ConnectionSettings(connectionPool,connection).DefaultIndex("project");
        settings.DisableDirectStreaming();
    var client = new ElasticClient(settings);
    var searchResponse = client.Search<Project>(s => s.MatchAll());

Expected output: response from inMemory elasticsearch Getting Error: JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Int64' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.

Upvotes: 2

Views: 270

Answers (1)

Rob
Rob

Reputation: 9979

Schema of total part in the response body changed between versions 6.x and 7.x of elasticsearch. If you want to make your response body working with NEST 6.x you will need to change total part from

..
total = new { value = 25 },
..

to

..
total = 25,
..

Full example:

var response = new
{
    took = 1,
    timed_out = false,
    _shards = new
    {
        total = 2,
        successful = 2,
        failed = 0
    },
    hits = new
    {
        total = 25,
        max_score = 1.0,
        hits = Enumerable.Range(1, 25).Select(i => (object)new
        {
            _index = "project",
            _type = "project",
            _id = $"Project {i}",
            _score = 1.0,
            _source = new { name = $"Project {i}" }
        }).ToArray()
    }
};

Hope that helps.

Upvotes: 2

Related Questions