【问题标题】:Do I need to create a Type for Nest Search?我需要为 Nest Search 创建一个类型吗?
【发布时间】:2014-08-05 22:30:36
【问题描述】:

我看到这样的例子:

var result = this._client.Search(s => s
.Index("my-index")
.Type("my-type")
 .Query(q=> ....)
 .Filter(f=> ....)         
);

但是当我使用它时,我得到:

The type arguments for method 'Nest.ElasticClient.Search<T>(System.Func<Nest.SearchDescriptor<T>,Nest.SearchDescriptor<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.   

我有很多不同的类型,我不想为所有类型创建类。我可以使用 NEST 并且它的搜索没有像 Search&lt;MyType&gt; 这样的类型吗?

谢谢

【问题讨论】:

    标签: c# database elasticsearch nest


    【解决方案1】:

    我已成功使用Search&lt;dynamic&gt; 来避免依赖特定类型。然后,当我得到我的结果时,我可以检查它们并在需要时转换/转换为特定的 POCO。

    我使用类似以下的东西:

    var result = client.Search<dynamic>(s => s
         .Index("myIndex")
         .AllTypes()
         .Query(q => ...)
         .Filter(f => ...)
    );
    
    foreach (var hit in result.Hits.Hits)
    {
         //check hit.Type and then map hit.Source into the appropriate POCO.
         // I use AutoMapper for the mapping, but you can do whatever suits you.
         if (string.Compare(hit.Type, "myType", StringCompare.OrdinalIgnoreCase) == 0)
         {
               var myType = AutoMapper.Mapper<MyType>(hit.Source);
         }
    }
    

    【讨论】:

    • 试过但需要一个例子:(
    • 编辑答案以包含示例。
    【解决方案2】:

    还有另一种解决方案。 NEST 5.x 及更低版本使用 Newtonsoft.Json 进行 JSON 序列化。所以你可以用JObject代替dynamic。

    var result = client.Search<JObject>(s => s
        .Index("music")
        .AllTypes()
        .Query(q => ...)
        .Filter(f => ...)
    );
    

    这非常有用,因为您现在可以使用 Newtonsoft.Json 功能将其转换为任何对象。

    private static Dictionary<string, Type> TypeMapping = new Dictionary<string, Type>
    {
        { "artist", typeof(Artist) },
        { "song", typeof(Song) }
    };
    
    ...
    
    foreach (var hit in result.Hits)
    {
        var type = TypeMapping[hit.Type];
        var result = hit.Source.ToObject(type);
    }
    

    NEST 6.x 附带有阴影的 Json.NET 依赖项。因此,要在此版本中使用 Newtonsoft.Json,您需要安装 NEST.JsonNetSerializer 包并指定 JsonNetSerializer.Default。

    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var connectionSettings =
        new ConnectionSettings(pool, sourceSerializer: JsonNetSerializer.Default);
    var client = new ElasticClient(connectionSettings);
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2013-07-01
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多