2014-09-12 41 views
0

我使用谷客戶端使用ElasticSearch。我想在ElasticSearch搜索:設置索引名在鳥巢SearchRequest類

SearchRequest countRequest = new SearchRequest 
{ 
    //Somthing 
}; 

client.Search<Post>(countRequest); 

在另一方面:

client.Search<Post>(s=>s.Index("IndexName").Query(...)) 

如何設置索引名通過SearchRequest類搜索?

回答

2

SearchRequest包含Indices屬性,以便您可以指定多個索引進行搜索。在你的情況,你可以只通過單一的指數,像這樣:

var request = new SearchRequest 
{ 
    Indices = new IndexNameMarker[] { "IndexName" } 
}; 

另一種辦法是給你的Post類型映射到其所屬的索引,並使用類型SearchRequest<T>讓NEST推斷索引名。

+1

這不工作在5.x版本 – Radu 2017-05-04 11:19:08

+0

@Radu可能太晚,但檢查我的答案。可能有幫助。它與5.6一起工作 – 2017-10-20 00:59:36

7

這是爲那些使用新版本的NEST。在2.0.1中,我無法找到SearchRequest中的Indices屬性。但是,你可以通過他們通過構造函數:

var request = new SearchRequest<Post>("IndexName", "TypeName"); 

我地圖上ConnectionSettings像這樣的指數和類型。

ConnectionSettings settings = new ConnectionSettings("url"); 
settings.MapDefaultTypeIndices(t => t.Add(typeof(Post), "IndexName")); 
settings.MapDefaultTypeNames(t => t.Add(typeof(Post), "TypeName")); 

其他的方式來告訴NEST指數和類型:

client.Search<Post>(s => s.Index("IndexName").Type("TypeName").From(0)); 

或類型的應用ElasticsearchTypeAttribute

[ElasticsearchType(Name = "TypeName")] 
public class Post{ } 
1

我想解決與ES v5(json請求被從文件中推送)有點不同的任務,但也有設置indexName相同的問題。所以,我的解決方案是添加index查詢字符串參數。在集成測試中使用這個:

public static class ElasticSearchClientHelper 
{ 
    public static ISearchResponse<T> SearchByJson<T>(this IElasticClient client, string json, string indexName, Dictionary<string, object> queryStringParams = null) where T : class 
    { 
     var qs = new Dictionary<string, object>() 
     { 
      {"index", indexName} 
     }; 
     queryStringParams?.ForEach(pair => qs.Add(pair.Key, pair.Value)); 

     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) 
     { 
      var searchRequest = client.Serializer.Deserialize<SearchRequest>(stream); 
      ((IRequestParameters)((IRequest<SearchRequestParameters>)searchRequest).RequestParameters).QueryString = qs; 
      return client.Search<T>(searchRequest); 
     } 
    } 
}