将 NEST (Elasticsearch) 搜索结果转换为数据集 - C#

Convert NEST (Elasticsearch) Search Results to DataSet - C#

我正在使用 NEST 搜索我的 Elasticsearch 索引:

        var result = client.Search<MyObject>(s => s
            .From(0)
            .Size(10)
            // Query here
);

这有效并且 returns 一个 Nest.SearchResponse 对象。 result.Hits.ToList()返回的格式为List<Nest.IHit<MyObject>>().

如何将返回的结果转换为 DataSet(或 DataTable)?

感谢任何帮助。

你需要循环你的结果

DataTable dt = new DataTable();
dt.Columns.Add("Field1", typeof(string));
dt.Columns.Add("Field2", typeof(string));
...
foreach (IHit<JObject> x in result.Hits)
{
   dt.Rows.Add(
       x.Fields.FieldValuesDictionary["Prop1"] as JArray,
       x.Fields.FieldValuesDictionary["Prop2"] as JArray
       ...
   );
}    

阅读

  • Retrieve data from elasticsearch results
  • How do you get search results returned in nest 1.x mapped to an object?

以及

DocumentsWithMetaData

When you do a search with NEST 0.12, you'd get back a QueryResponse with two ways to loop over your results. .Documents is an IEnumerable and .DocumentsWithMetaData is and IEnumerable> depending on your needs one of them might be easier to use.

Starting from NEST 1.0 .DocumentsWithMetaData is now called simply .Hits.

http://nest.azurewebsites.net/breaking-changes.html

如本 article 中所建议,您可以使用扩展方法将 IEnumerable<T> 转换为 DataTable

public static class IEnumerableExtensions
{
    /*Converts IEnumerable To DataTable*/
    public static DataTable ToDataTable<TSource>(this IEnumerable<TSource> data)
    {
        DataTable dataTable = new DataTable(typeof(TSource).Name);
        PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in props)
        {
            dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ??
                prop.PropertyType);
        }

        foreach (TSource item in data)
        {
            var values = new object[props.Length];
            for (int i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        return dataTable;
    }  
}

然后,在搜索之后你可以这样做:

var dataTable = result.Documents.ToDataTable();

其中 Documents 是一个 IEnumerable<MyObject>,即返回的命中中的文档。获取这些文件的另一种方法是:

var documents=result.Hits.Select(h => h.Source);