ElasticSearch NEST client not returning results

2020-02-25 22:57发布

问题:

I am running a simple query through the ElasticSearch NEST C# client. I receive results when I run the same query through http, but I get zero documents returned from the client.

This is how I populated the data set:

curl -X POST "http://localhost:9200/blog/posts" -d @blog.json

This POST request returns a JSON result:

http://localhost:9200/_search?q=adipiscing

This is the code I have that is not returning anything.

public class Connector
{
    private readonly ConnectionSettings _settings;
    private readonly ElasticClient _client;

    public Connector()
    {
        _settings = new ConnectionSettings("localhost", 9200);
        _settings.SetDefaultIndex("blog");
        _client = new ElasticClient(_settings);
    }

    public IEnumerable<BlogEntry> Search(string q)
    {
        var result =
            _client.Search<BlogEntry>(s => s.QueryString(q));

        return result.Documents.ToList();
    }
}

What am I missing? Thanks in advance ..

回答1:

NEST tries to guess the type and index name and in your case it will use /blog/blogentries

blog because that what you told the default index is and blogentries because it will lowercase and pluralize the type name you pass to Search<T>.

You can control which type and index like so:

 .Search<BlogEntry>(s=>s.AllIndices().Query(...));

This will let NEST know you actually want to search on all indices and so nest will translate it to /_search on the root, equal to the command you issued on curl.

What you most likely want is:

 .Search<BlogEntry>(s=>s.Type("posts").Query(...));

So that NEST searches in /blog/posts/_search