[英]Do I need to create a Type for Nest Search?
I see examples like: 我看到类似的例子:
var result = this._client.Search(s => s
.Index("my-index")
.Type("my-type")
.Query(q=> ....)
.Filter(f=> ....)
);
But when I use this I get: 但是当我使用它时,我得到:
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.
I have lots of different types and I don't want to create classes for all of them. 我有很多不同的类型,我不想为所有这些都创建类。 Can I use NEST and it's search without types like
Search<MyType>
? 我可以使用NEST进行搜索,而不使用
Search<MyType>
类的类型吗?
Thanks 谢谢
I have successfully used Search<dynamic>
to avoid needing to be dependent upon a specific type. 我已经成功使用
Search<dynamic>
来避免依赖于特定类型。 Then when I get my results back I can examine them and cast/convert into a specific POCO if desired. 然后,当我取回结果时,可以检查它们并将其转换/转换为特定的POCO(如果需要)。
I use something like the following: 我使用如下内容:
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);
}
}
There is one more solution. 还有另一种解决方案。 NEST 5.x and less uses Newtonsoft.Json for JSON serialization.
NEST 5.x及以下版本使用Newtonsoft.Json进行JSON序列化。 So you can use
JObject
instead of dynamic
. 因此,您可以使用
JObject
而不是dynamic
。
var result = client.Search<JObject>(s => s
.Index("music")
.AllTypes()
.Query(q => ...)
.Filter(f => ...)
);
This is very useful because you can convert it now to any object using Newtonsoft.Json functionality. 这非常有用,因为您现在可以使用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 ships with a shaded Json.NET dependency. NEST 6.x附带有阴影的Json.NET依赖项。 So in order to use Newtonsoft.Json for this version you need to install NEST.JsonNetSerializer package and specify
JsonNetSerializer.Default
. 因此,要在此版本中使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.