.net – 使用LINQ处理弹性搜索结果
使用LINQ处理ElasticSearch结果的最有效方法是什么?
我遇到了JSON.Net的JObject Class. 从ElasticSearch返回的JSON是否通过JObject类以适合LINQ查询的方式构建? 解决方法
这是关于如何利用LINQ处理来自elasticsearch引擎的JSON查询结果的完整解决方案.
连接库 – PlainElastic.NET 首先,我将PlainElastic.NET用于一个目的:连接到我的elasticsearch服务器.该库非常精简,包含简洁的GET,POST和PUT功能.这将在下面与客户端连接对象发挥作用. result.ToString()提供来自elasticsearch服务器的JSON响应.只需将DLL打入您的bin并添加引用即可. JSON处理器 – JSON.NET 我正在使用NewtonSoft JSON.NET的一个很棒的功能来促进LINQ查询.该库有一个JObject类,它提供了一个可嵌套的可查询结构来执行LINQ.请参阅下面的行,我抓住HitCount以查看获取单个值有多好,当然,请查看LINQ查询以查看如何查询它.请记住,这只是一个数据结构,它是解析JSON字符串的结果.只需将DLL打入您的bin并添加引用即可. 执行针对弹性搜索的查询 'Execute the Search Dim client = New ElasticConnection("localhost",9200) Dim result = client.Post("myindex/mytype/_search",elastic_query) 'elastic_query = well-formatted elasticsearch query (json string)' Dim J As JObject = JObject.Parse(result.ToString()) 'How many results were located? Dim HitCount = CInt(J("hits")("total")) 'What was the maximum score? Maybe you want to know this for normalizing scores to 0-100. ' - We make sure we have hits first ' - Also,make sure scoring is turned on. It might be turned off if an alternate sort method is used in your query If HitCount > 0 AndAlso J("hits")("max_score").Type <> JTokenType.Null Then MaxScore = CDbl(J("hits")("max_score")) 使用LINQ处理结果 现在,使用LINQ提供一个漂亮的匿名对象来绑定到Gridviews,DataLists,Repeater等.我有意提供了一个非平凡的LINQ查询示例.此示例获取嵌套数据(商店,类别) Dim SearchResults = _ (From X In J("hits")("hits") Select score = CDec(If(X("_score").Type = JTokenType.Null,X("_score"))),boost = CDbl(X("_source")("_boost")),InstitutionID = CInt(X("_source")("InstitutionID")),Name = CStr(X("_source")("Name")),Stores = (From S In X("_source")("Stores") Select CInt(S("StoreID"))).ToList(),Categories = (From Z In X("_source")("Categories") Select CatID = CInt(Z("CatID")),CatName = CStr(Z("CatName")),InstitutionID = CInt(X("_source")("InstitutionID"))).ToList() Order By score Descending,boost Descending ) 现在,您可以绑定到Repeater,DataList或Gridview MyRepeater.DataSource = SearchResults MyRepeater.DataBind() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |