Exemplo n.º 1
0
        /// <summary>
        /// 使用sql语句查询(含分页)
        /// </summary>
        /// <param name="eSContext"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public ESPageInfo <T> QueryBySql(ESSqlSearchOption option)
        {
            var data = new ESPageInfo <T>();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("");

                StringContent       content = new StringContent(JsonConvert.SerializeObject(new { sql = option.Sql }), Encoding.UTF8, "application/json");
                HttpResponseMessage msg     = client.PostAsync("_sql", content).Result;
                if (msg.StatusCode != HttpStatusCode.OK)
                {
                    return(data);
                }

                string  result   = msg.Content.ReadAsStringAsync().Result;
                dynamic response = JsonConvert.DeserializeObject <dynamic>(result);
                data.DataCount = Convert.ToInt32(response.hits.total);
                data.PageIndex = option.PageIndex;
                data.PageSize  = option.PageSize;
                List <dynamic> hits = JsonConvert.DeserializeObject <List <dynamic> >(response.hits.hits.ToString());
                data.DataSource = hits.Select(o =>
                                              new ESModel <T>()
                {
                    UniqueId = o._id.ToString(),
                    Data     = JsonConvert.DeserializeObject <T>(o._source.ToString())
                }
                                              ).ToList();
                return(data);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 查询列表(by page)
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public ESPageInfo <T> Query(ESSearchOption option)
        {
            ISearchRequest searchRequest   = new SearchRequest <T>(Indices.Parse(option.IndexName), Types.Parse(option.TypeName));
            var            data            = new ESPageInfo <T>();
            var            queryCondations = BuildQueryContainer(option.Where, option.Analyzer);
            var            shouldQuerys    = queryCondations.Should;
            var            mustQuerys      = queryCondations.Must;
            var            mustNot         = queryCondations.MustNot;

            #region +多条件模糊匹配
            searchRequest.Query = new BoolQuery()
            {
                Should  = shouldQuerys,
                Must    = mustQuerys,
                MustNot = mustNot,
            };

            if (option.ESHighLightConfig != null)
            {
                searchRequest.Highlight = BuildHightLight(option.Where.Select(o => o.Key).ToList(), option.ESHighLightConfig);
            }
            #endregion

            #region +多字段排序
            if (option.OrderDic != null)
            {
                List <ISort> orderFileds = new List <ISort>();
                foreach (var item in option.OrderDic)
                {
                    orderFileds.Add(new SortField()
                    {
                        Field = item.Key,
                        Order = item.Value ? SortOrder.Descending : SortOrder.Ascending,
                    });
                }
                searchRequest.Sort = orderFileds;
            }
            #endregion

            #region +组装结果集
            searchRequest.From = (option.PageIndex - 1) * option.PageSize;
            searchRequest.Size = option.PageSize;
            var result = _es.Search <T>(searchRequest);
            data.DataCount  = Convert.ToInt32(result.Total);
            data.PageIndex  = option.PageIndex;
            data.PageSize   = option.PageSize;
            data.DataSource = new List <ESModel <T> >();
            //判断时候需要改良匹配
            if (option.ESHighLightConfig == null)
            {
                data.DataSource = result.Hits.Select(o =>
                                                     new ESModel <T>()
                {
                    UniqueId  = o.Id,
                    Data      = o.Source,
                    Score     = o.Score,
                    IndexName = o.Index,
                    TypeName  = o.Type
                }).ToList();
            }
            else
            {
                IReadOnlyCollection <IHit <T> > hits = result.Hits;  //找到高亮列表
                foreach (var hit in hits)
                {
                    var currentHightList = hit.Highlights;
                    if (hit.Source is Dictionary <string, object> )
                    {
                        Dictionary <string, object> currentSource = hit.Source as Dictionary <string, object>;
                        List <string> keys = currentSource.Keys.ToList();
                        foreach (var key in keys)
                        {
                            KeyValuePair <string, HighlightHit> currentMatch = currentHightList.FirstOrDefault(o => o.Key.ToLower() == key.ToLower());
                            if (currentMatch.Key != null)
                            {
                                currentSource[key] = currentMatch.Value.Highlights.First();
                            }
                        }
                    }
                    else
                    {
                        var sourceProps = hit.Source.GetType().GetProperties();
                        foreach (var sourceProp in sourceProps)
                        {
                            KeyValuePair <string, HighlightHit> currentMatch = currentHightList.FirstOrDefault(o => o.Key == sourceProp.Name);
                            if (currentMatch.Key != null)
                            {
                                sourceProp.SetValue(hit.Source, Convert.ChangeType(currentMatch.Value.Highlights.First(), sourceProp.PropertyType));
                            }
                        }
                    }
                    data.DataSource.Add(new ESModel <T>()
                    {
                        Data      = hit.Source,
                        UniqueId  = hit.Id,
                        Score     = hit.Score,
                        IndexName = hit.Index,
                        TypeName  = hit.Type
                    });
                }
            }
            #endregion

            return(data);
        }