Matt
Matt

Reputation: 719

Inconsistent Elastic Search results using Nest in basic hello world application

I created this app to test the basic functionality of ES & Nest, all of it was copied from Nest's tutorial site.

If I set a breakpoint and step through the code it works fine but if I let it run without stepping it returns 0 documents and blows up. Does ES need a moment to index the document or something?

Thank you. This is ES 2.1.1

using System;
using System.Linq;
using Nest;

namespace NestTest
{
public class Person
{
    public string id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var node = new Uri("http://localhost:9200");

        var settings = new ConnectionSettings(
            node,
            defaultIndex: "my-application"
        );

        var client = new ElasticClient(settings);

        client.DeleteIndex("my-application");

        var person = new Person
        {
            id = "1",
            firstname = "martijn",
            lastname = "laarman"
        };

        client.Index(person);

        var searchResults = client.Search<Person>(s => s
           .From(0)
           .Size(10)
           .Query(q => q
               .Term(p => p.firstname, "martijn")
           )
           );

        // this is 0 most of the time
        Console.WriteLine("Document count = {0}", searchResults.Documents.Count());

        var martijn = GetMartijn(client);
        ShowMartijn(martijn);

    }

    private static void ShowMartijn(Person m)
    {
        Console.WriteLine(string.Format("{0} {1}", m.firstname, m.lastname));
    }

    private static Person GetMartijn(ElasticClient client)
    {
        var searchResults = client.Search<Person>(s => s
            .From(0)
            .Size(10)
            .Query(q => q
                .Term(p => p.firstname, "martijn")
            )
            );
        return searchResults.Documents.First();
    }
}
}

Upvotes: 0

Views: 73

Answers (1)

bittusarkar
bittusarkar

Reputation: 6357

It returns zero documents because Elasticsearch takes some time for the indexed document to be searchable. Out of the box, it is 1 second. This is the default refresh interval. There is no such delay in your code and hence the difference in observation when you step through your code vs letting it run free. To make sure the indexed documents are searchable, force a refresh as under before invoking the Search() command:

client.Refresh();

Your code blows up most probably due to the faulty assumption in the line

return searchResults.Documents.First();

This assumes that Documents is not empty. To make the code more reliable, you can check the value of Count property of Documents before using First(). But then this is just a Hello World program :)

Upvotes: 2

Related Questions