nest:使用must和a constraint约束构建QueryContainer请求

时间:2017-01-30 10:53:47

标签: elasticsearch nest

我尝试使用must和a should请求构建一个elasticsearch请求 我的目标要求如下:

POST /index/type/_search
{
  "query": {
    "bool" : {
      "must" : {
         "match":{"field1":{"query":"word1"}}
      },
      "should":{
        "match":{"field2":{"query":"word2"}}
      }
    }
  }}

我写道:

 var queryContainer = new QueryContainer();
 queryContainer &= new MatchQuery() { Field = "field1", Query = "word1" };
 queryContainer |= new MatchQuery() { Field = "field2", Query = "word2"};


var searchRequest = new SearchRequest<type>
        {
            Query = queryContainer
        };

但是它让我产生了:

POST /index/type/_search
{
  "query":{
    "bool":{
      "should":[
        {"match":{"field1":{"query":"word1"}}},
        {"match":{"field2":{"query":"word2"}}}]
    }
  }
}

在构建QueryContainer时,您知道我应该写些什么吗?

1 个答案:

答案 0 :(得分:2)

在这里使用运算符重载没有用;我认为在这种情况下,构建bool查询更清晰

对象初始化程序语法

var searchRequest = new SearchRequest<Document>()
{
    Query = new BoolQuery
    {
        Must = new QueryContainer[] { new MatchQuery() { Field = "field1", Query = "word1" } },
        Should = new QueryContainer[] { new MatchQuery() { Field = "field2", Query = "word2" } }
    }
};

client.Search<Document>(searchRequest);

或Fluent API

client.Search<Document>(s => s
    .Query(q => q
        .Bool(b => b
            .Must(fi => fi
                .Match(m => m
                      .Field("field2")
                      .Query("word2")
                )
            )
            .Should(sh => sh
                .Match(m => m
                      .Field("field1")
                      .Query("word1")
                )
            )
        )
    )
);