1. 程式人生 > >Elasticsearch.Net 多層嵌套的邏輯實現

Elasticsearch.Net 多層嵌套的邏輯實現

.com arc 分享 sts req bsp match 關系 http

原文:Elasticsearch.Net 多層嵌套的邏輯實現

技術分享圖片

{
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "to_province": "河南"
          }
        },
        {
          "match_phrase": {
            "to_city": "信陽市"
          }
        },
        {
          "match_phrase": {
            "to_district": "新縣"
          }
        },
        {
          "bool": {
            "should": [
              {
                "match_phrase": {
                  "from_city": "商丘市"
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "from_city"
                    }
                  }
                }
              }
            ]
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}

查詢條件:前面3個是and關系,後面4和5是或者關系,

            ElasticsearchProvider provider = new ElasticsearchProvider();
            ElasticsearchProvider es = new ElasticsearchProvider();

            var elasticsearchPage = new ElasticsearchPage<AreaJiBao>(AreaJiBao.IndexName)
            {
                PageIndex 
= 1, PageSize = 20 }; var searchRequest = elasticsearchPage.InitSearchRequest(); var predicateList = new List<IPredicate> { Predicates.Field<AreaJiBao>(x => x.ToProvince, ExpressOperator.Like, "河南省
"), Predicates.Field<AreaJiBao>(x => x.ToCity, ExpressOperator.Like, "信陽市"), Predicates.Field<AreaJiBao>(x => x.ToCity, ExpressOperator.Like, "新縣") }; // 前面3個是 and 關系 var predicate = Predicates.Group(GroupOperator.And, predicateList.ToArray()); // FromCity要不包含商丘市,要不就為空值 var predicateListExists = new List<IPredicate> { Predicates.Field<AreaJiBao>(x => x.FromCity, ExpressOperator.MustNotExists, null) }; var predicateExists = Predicates.Group(GroupOperator.Or, predicateListExists.ToArray()); var predicateListTerm = new List<IPredicate> { Predicates.Field<AreaJiBao>(x => x.FromCity, ExpressOperator.Like, "商丘市") }; var predicateOr = Predicates.Group(GroupOperator.Or, predicateListTerm.ToArray()); var predicatecCombinationChild = new List<IPredicate> { predicateExists, predicateOr }; var pgCombinationChild = Predicates.Group(GroupOperator.Or, predicatecCombinationChild.ToArray()); // 查詢 var predicatecCombination = new List<IPredicate> { predicate, pgCombinationChild }; var pgCombination = Predicates.Group(GroupOperator.And, predicatecCombination.ToArray()); searchRequest.InitQueryContainer(pgCombination); var data = provider.SearchPage(searchRequest); foreach (var item in data.Documents) { Console.WriteLine($"{item.Id}"); }

Elasticsearch.Net 多層嵌套的邏輯實現