ElasticSearch NEST Query

北城以北 提交于 2019-12-28 13:56:52

问题


I'm trying to mimic a query that I wrote in Sense (chrome plugin) using NEST in C#. I can't figure out what the difference between the two queries is. The Sense query returns records while the nest query does not. The queries are as follows:

var searchResults = client.Search<File>(s => s.Query(q => q.Term(p => p.fileContents, "int")));

and

{
"query": {
    "term": {
       "fileContents": {
          "value": "int"
       }
    }
}

What is the difference between these two queries? Why would one return records and the other not?


回答1:


You can find out what query NEST uses with the following code:

var json = System.Text.Encoding.UTF8.GetString(searchResults.RequestInformation.Request);

Then you can compare the output.




回答2:


I prefer this slightly simpler version, which I usually just type in .NET Immediate window:

searchResults.ConnectionStatus;

Besides being shorter, it also gives the url, which can be quite helpful.

? searchResults.ConnectionStatus;
{StatusCode: 200, 
    Method: POST, 
    Url: http://localhost:9200/_all/filecontent/_search, 
    Request: {
  "query": {
    "term": {
      "fileContents": {
        "value": "int"
      }
    }
  }
}



回答3:


Try this:

var searchResults2 = client.Search<File>(s => s
    .Query(q => q
        .Term(p => p.Field(r => r.fileContents).Value("int")
    )
));

Followup:

  1. RequestInformation is not available in newer versions of NEST.
  2. I'd suggest breaking down your code in steps (Don't directly build queries in client.Search() method.

client.Search() takes Func<SearchDescriptor<T>, ISearchRequest> as input (parameter).

My answer from a similar post:

SearchDescriptor<T> sd = new SearchDescriptor<T>()
.From(0).Size(100)
    .Query(q => q
        .Bool(t => t
            .Must(u => u
                .Bool(v => v
                    .Should(
                        ...
                    )
                )
            )
        )
    );

And got the deserialized JSON like this:

{
  "from": 0,
  "size": 100,
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              ...
            ]
          }
        }
      ]
    }
  }
}

It was annoying, NEST library should have something that spits out the JSON from request. However this worked for me:

using (MemoryStream mStream = new MemoryStream()) {
    client.Serializer.Serialize(sd, mStream);
    Console.WriteLine(Encoding.ASCII.GetString(mStream.ToArray()));
}

NEST library version: 2.0.0.0. Newer version may have an easier method to get this (Hopefully).



来源:https://stackoverflow.com/questions/29376817/elasticsearch-nest-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!