2017-08-04 189 views
0

我创造这个功能:我如何使用ElasticSeach(C#/ NEST)搜索多个索引?

  public static ISearchResponse<Immo> searchImmoByCustomerField(Nest.ElasticClient esClient, string esIndex, string esIndex2, int from, int take, string qField, string nmqField, string qTerm, string nmqTerm) 
      { 
       var result = esClient.Search<Immo>(s => s 
         .AllIndices() 
          .Query(q => q 
           .Indices(i => i 
            .Indices(new[] { esIndex, esIndex2 }) 
            .Query(iq => iq.Term(qField, qTerm)) 
            .NoMatchQuery(iq => iq.Term(nmqField, nmqTerm)) 
           ) 
          ) 
       ); 
       return result; 
      } 

功能寻找在2个指数搜索词。 Visual Studio中告诉我的消息:

“不赞成。您可以在查询中指定_index针对特定指数”

但我怎么能做到这一点?

+0

你所需要的'NoMatchQuery'查询?由于弃用来自Elasticsearch 5本身,因此不推荐使用[index query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-indices-query.html) – Slomo

回答

2

indices query is deprecated因此它仍然可以正常工作,但弃用可能会在将来的主要版本中被删除。

可以实现相同的功能指标与

var esIndex = "index-1"; 
var esIndex2 = "index-2"; 
var qField ="query-field"; 
var qTerm = "query-term"; 
var nmqField = "no-match-query-field"; 
var nmqTerm = "no-match-query-term"; 

client.Search<Immo>(s => s 
    .AllIndices() 
    .Query(q => (q 
     .Term(t => t 
      .Field(qField) 
      .Value(qTerm) 

     ) && +q 
     .Terms(t => t 
      .Field("_index") 
      .Terms(new[] { esIndex, esIndex2 }) 
     )) || (q 
     .Term(t => t 
      .Field(nmqField) 
      .Value(nmqTerm) 
     ) && !q 
     .Terms(t => t 
      .Field("_index") 
      .Terms(new[] { esIndex, esIndex2 }) 
     )) 
    ) 
); 

产生以下查询JSON

POST http://localhost:9200/_all/immo/_search 
{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "bool": { 
      "must": [ 
       { 
       "term": { 
        "query-field": { 
        "value": "query-term" 
        } 
       } 
       } 
      ], 
      "filter": [ 
       { 
       "terms": { 
        "_index": [ 
        "index-1", 
        "index-2" 
        ] 
       } 
       } 
      ] 
      } 
     }, 
     { 
      "bool": { 
      "must": [ 
       { 
       "term": { 
        "no-match-query-field": { 
        "value": "no-match-query-term" 
        } 
       } 
       } 
      ], 
      "must_not": [ 
       { 
       "terms": { 
        "_index": [ 
        "index-1", 
        "index-2" 
        ] 
       } 
       } 
      ] 
      } 
     } 
     ] 
    } 
    } 
}