2017-08-04 79 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" 
        ] 
       } 
       } 
      ] 
      } 
     } 
     ] 
    } 
    } 
}