ElasticSearch NEST Query

2019-01-18 07:23发布

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?

3条回答
狗以群分
2楼-- · 2019-01-18 07:44

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.

查看更多
三岁会撩人
3楼-- · 2019-01-18 07:44

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"
      }
    }
  }
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-18 07:52

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).

查看更多
登录 后发表回答