Exemple #1
0
        public ISearchResponse <T> Query(QueryDes qd)
        {
            var s = new SearchDescriptor <T>().Index(_config.ES_INDEX).Type(_config.ES_TYPE).From(qd.From).Take(qd.Take)
                    .Source(sr => GetSource(sr, qd))
                    .Query(q => GetQuery(q, qd));

            if (qd.SortField != null)
            {
                if (qd.IsAsc)
                {
                    s.Sort(st => st.Ascending(qd.SortField));
                }
                else
                {
                    s.Sort(st => st.Descending(qd.SortField));
                }
            }

            if (qd.TerminateAfter > 0)                  // 设置单个节点上的数据查询截断阈值,提高响应速度(但会导致数据搜索不全面)
            {
                s.TerminateAfter(qd.TerminateAfter);
            }

            if (qd.Aggs != null)
            {
                s.Aggregations(agg => Get_Agg(agg, qd));
            }

            if (qd.HLPreTag != null)
            {
                s.Highlight(hl => Get_HL(hl, qd));
            }

            return(_client.Search <T>(s));
        }
        /// <summary>
        /// 私有方法,构造高亮查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageParams"></param>
        /// <param name="searchDescriptor"></param>
        private void BuildHighLightQuery <T>(IPageParam pageParams, ref SearchDescriptor <T> searchDescriptor) where T : class
        {
            int keysLength = (pageParams.Highlight?.Keys?.Length).Value;

            Func <HighlightFieldDescriptor <T>, IHighlightField>[] filedDesciptor = new Func <HighlightFieldDescriptor <T>, IHighlightField> [keysLength];
            int keysIndex = 0;

            foreach (string key in pageParams.Highlight?.Keys)
            {
                filedDesciptor[keysIndex] = hf => hf.Field(key)//简介高亮
                                            .HighlightQuery(q => q
                                                            .Match(m => m
                                                                   .Field(key)
                                                                   .Query(pageParams.KeyWord)));
                keysIndex++;
            }
            //构造hightlight
            IHighlight highLight = new HighlightDescriptor <T>()
                                   .PreTags(pageParams.Highlight.PreTags)
                                   .PostTags(pageParams.Highlight.PostTags)
                                   .Fields(filedDesciptor);

            //设置高亮
            searchDescriptor = searchDescriptor.Highlight(s => highLight);
        }
 protected virtual void ApplyHighlight <T>(SearchDescriptor <T> searchRequest) where T : class
 {
     searchRequest
     .Highlight(hd => hd
                .Fields(ff => ff
                        .Field("*")
                        .PreTags(SearchConstants.Global.HighlightPreTag)
                        .PostTags(SearchConstants.Global.HighlightPostTag))
                );
 }
Exemple #4
0
 /// <summary>
 /// 给关键词添加高亮
 /// </summary>
 public static SearchDescriptor <T> AddHighlightWrapper <T>(this SearchDescriptor <T> sd,
                                                            string pre = "<em>", string after = "</em>",
                                                            params Func <HighlightFieldDescriptor <T>, IHighlightField>[] fieldHighlighters)
     where T : class, IElasticSearchIndex
 {
     if (fieldHighlighters.Length <= 0)
     {
         throw new Exception("关键词高亮,但是没有指定高亮字段");
     }
     return(sd.Highlight(x => x.PreTags(pre).PostTags(after).Fields(fieldHighlighters)));
 }
Exemple #5
0
        public virtual async Task <ISearchResponse <T> > SearchAsync <T, TKey>(string indexName, SearchDescriptor <T> query, int skip, int size, string[] includeFields = null,
                                                                               string preTags   = "<strong style=\"color: red;\">", string productTags = "</strong>",
                                                                               bool disableHigh = false, params string[] highField) where T : ElasticEntity <TKey>
        {
            query.Index(indexName);
            var highdes = new HighlightDescriptor <T>();

            if (disableHigh)
            {
                preTags     = "";
                productTags = "";
            }
            highdes.PreTags(preTags).PostTags(productTags);

            var ishigh = highField != null && highField.Length > 0;

            var hfs = new List <Func <HighlightFieldDescriptor <T>, IHighlightField> >();

            //Pagination
            query.Skip(skip).Take(size);
            //Keyword highlighting
            if (ishigh)
            {
                foreach (var s in highField)
                {
                    hfs.Add(f => f.Field(s));
                }
            }

            highdes.Fields(hfs.ToArray());
            query.Highlight(h => highdes);
            if (includeFields != null)
            {
                query.Source(ss => ss.Includes(ff => ff.Fields(includeFields.ToArray())));
            }


            var data     = JsonConvert.SerializeObject(query);
            var response = await ElasticSearchClient.SearchAsync <T>(query);


            return(response);
        }
        /// <summary>
        /// 构造高亮查询
        /// </summary>
        private void BuildHighLightQuery <T>(IPageParam param, ref SearchDescriptor <T> searchRequest) where T : class
        {
            var keysLength      = param.Highlight?.Keys?.Length ?? 0;
            var fieldDescriptor = new Func <HighlightFieldDescriptor <T>, IHighlightField> [keysLength];
            var keysIndex       = 0;

            foreach (var key in param.Highlight?.Keys)
            {
                fieldDescriptor[keysIndex] = hf => hf.Field(key)
                                             .HighlightQuery(q => q.Match(m => m.Field(key).Query(param.Keyword)));
                keysIndex++;
            }

            IHighlight highlight = new HighlightDescriptor <T>()
                                   .PreTags(param.Highlight.PreTags)
                                   .PostTags(param.Highlight.PostTags)
                                   .Fields(fieldDescriptor);

            searchRequest = searchRequest.Highlight(s => highlight);
        }
        /// <summary>
        /// search
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="indexName"></param>
        /// <param name="query"></param>
        /// <param name="skip">skip num</param>
        /// <param name="size">return document size</param>
        /// <param name="includeFields">return fields</param>
        /// <param name="preTags">Highlight tags</param>
        /// <param name="postTags">Highlight tags</param>
        /// <param name="disableHigh"></param>
        /// <param name="highField">Highlight fields</param>
        /// <returns></returns>
        public virtual async Task <ISearchResponse <T> > SearchAsync <T, TKey>(string indexName, SearchDescriptor <T> query,
                                                                               int skip, int size, string[] includeFields = null,
                                                                               string preTags = "<strong style=\"color: red;\">", string postTags = "</strong>", bool disableHigh = false,
                                                                               params string[] highField) where T : class
        {
            query.Index(indexName);
            var highlight = new HighlightDescriptor <T>();

            if (disableHigh)
            {
                preTags  = "";
                postTags = "";
            }

            highlight.PreTags(preTags).PostTags(postTags);

            var isHigh = highField != null && highField.Length > 0;

            var hfs = new List <Func <HighlightFieldDescriptor <T>, IHighlightField> >();

            //分页
            query.Skip(skip).Take(size);
            //关键词高亮
            if (isHigh)
            {
                foreach (var s in highField)
                {
                    hfs.Add(f => f.Field(s));
                }
            }

            highlight.Fields(hfs.ToArray());
            query.Highlight(h => highlight);
            if (includeFields != null)
            {
                query.Source(ss => ss.Includes(ff => ff.Fields(includeFields.ToArray())));
            }
            var response = await _esClient.SearchAsync <T>(query);

            return(response);
        }
Exemple #8
0
        private static void Query()
        {
            PrepareES(client =>
            {
                var temp  = new ProductListV2();
                var sd    = new SearchDescriptor <ProductListV2>();
                var query = new QueryContainer();
                query     = query && new MatchQuery()
                {
                    Field = nameof(temp.SeachTitle), Query = "机油"
                };
                sd = sd.Query(x => query);
                sd = sd.Skip(0).Take(100);

                sd = sd.Highlight(x => x.PreTags("<span class='hit'>").PostTags("</span>")
                                  .Fields(f => f.Field(fd => fd.ShopName)));

                var queryresponse = client.Search <ProductListV2>(x => sd);
                if (queryresponse.IsValid)
                {
                    var list = queryresponse?.Hits.Select(x => x.Source).Where(x => x != null).ToList();
                    if (ValidateHelper.IsPlumpList(list))
                    {
                        foreach (var model in list)
                        {
                            Console.WriteLine(model.SeachTitle);
                        }
                    }
                    else
                    {
                        Console.WriteLine("没有找到数据");
                    }
                }
                else
                {
                    Console.WriteLine("查询失败");
                }
                Console.ReadLine();
                return(true);
            });
        }
Exemple #9
0
        /// <summary>
        /// 给关键词添加高亮
        /// </summary>
        public static SearchDescriptor <T> AddHighlightWrapper <T>(this SearchDescriptor <T> sd,
                                                                   string preHtmlTag, string postHtmlTag, Func <HighlightFieldDescriptor <T>, IHighlightField>[] fieldHighlighters)
            where T : class, IESIndex
        {
            if (ValidateHelper.IsEmpty(fieldHighlighters))
            {
                throw new Exception("关键词高亮,但是没有指定高亮字段");
            }
            sd = sd.Highlight(x => x.PreTags(preHtmlTag).PostTags(postHtmlTag).Fields(fieldHighlighters));

            /*
             * sd.Highlight(x => x.PreTags(pre).PostTags(after)
             * .Fields(f => f
             * .Field("comment")
             * .HighlightQuery(q =>
             * q.Match(m => m.Query("keywords")
             * .Operator(Operator.Or).Analyzer("ik_smart").MinimumShouldMatch("100%")))));
             */

            return(sd);
        }
        /// <summary>
        /// 高亮设置失败的方法
        /// </summary>
        /// <param name="client"></param>
        /// <param name="queryString"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageResult <MainRCJournalInfo> PageResultSearcher2(string queryString, int pageIndex, int pageSize)
        {
            var query = new SearchDescriptor <MainRCJournalInfo>();

            query.PostFilter(x => x.Match(f => f.Field(obj => obj.TITLE).Query(queryString)));
            query.Highlight(h => h
                            .PreTags("<b>")
                            .PostTags("</<b>")
                            .Encoder("Html")
                            .Fields(
                                f => f.Field(obj => obj.TITLE),
                                f => f.Field(obj => obj.PUBLISHING_PLACE),
                                f => f.Field("_all")
                                )
                            );
            query.Sort(x => x.Field("_score", SortOrder.Descending));
            var s_result = client.Search <MainRCJournalInfo>(x => query.Size(pageSize).From((pageIndex - 1) * pageSize));

            var list = s_result.Hits.Select(c => new MainRCJournalInfo()
            {
                ID                = c.Source.ID,
                TITLE             = c.Highlights == null ? c.Source.TITLE : c.Highlights.Keys.Contains("TITLE") ? string.Join("", c.Highlights["TITLE"].Highlights) : c.Source.TITLE,
                PUBLISHING_PLACE  = c.Highlights == null ? c.Source.TITLE : c.Highlights.Keys.Contains("publishing_place") ? string.Join("", c.Highlights["publishing_place"].Highlights) : c.Source.TITLE,
                PUBLISHER         = c.Source.PUBLISHER,
                PUBLISHING_PERIOD = c.Source.PUBLISHING_PERIOD,
            });
            PageResult <MainRCJournalInfo> result = new PageResult <MainRCJournalInfo>()
            {
                TotalCount = PageCount2(client, queryString, new SearchDescriptor <MainRCJournalInfo>()),
                PageIndex  = pageIndex,
                PageSize   = pageSize,
                DataList   = list.ToList()
            };

            return(result);
        }
        public static SearchDescriptor <T> UpdateSearchDescriptor <T>(this SearchDescriptor <T> selector,
                                                                      Index index, SearchRequest request, string preAndPostTag)
            where T : class
        {
            // Validate parameters.
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (index == null)
            {
                throw new ArgumentNullException(nameof(index));
            }
            if (string.IsNullOrWhiteSpace(preAndPostTag))
            {
                throw new ArgumentNullException(nameof(preAndPostTag));
            }
            request.Validate();

            // Start updating.
            selector = selector.
                       Index(Indices.Index(new [] { index.Name })).
                       Type <T>();

            // Set take, skip.
            if (request.Skip > 0)
            {
                selector = selector.Skip(request.Skip);
            }
            if (request.Take != null)
            {
                selector = selector.Size(request.Take.Value);
            }

            // Minimum score.
            if (request.MinimumScore != null)
            {
                selector = selector.MinScore((double)request.MinimumScore.Value);
            }

            // Query all of the fields.
            selector = selector.Query(
                q => q.Bool(
                    b => b.
                    Should(request.QueryStringQuery <T>()).
                    Filter(request.Filter <T>())
                    )
                );

            // Highlight, if desired.
            if (request.Highlight)
            {
                // Highlight.
                selector = selector.Highlight(
                    h => h
                    .PreTags(preAndPostTag)
                    .PostTags(preAndPostTag)
                    .NumberOfFragments(0)
                    .RequireFieldMatch(false)
                    .Fields(f => f.Field("*"))
                    );
            }

            // Return the descriptor.
            return(selector);
        }
Exemple #12
0
 /// <summary>
 /// 给关键词添加高亮
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="sd"></param>
 /// <param name="pre"></param>
 /// <param name="after"></param>
 public static void AddHighlightWrapper <T>(this SearchDescriptor <T> sd, string pre = "<em>", string after = "</em>") where T : class
 {
     sd.Highlight(x => x.PreTags(pre).PostTags(after));
 }
Exemple #13
0
 public static SearchDescriptor <dynamic> AddHighlighting(this SearchDescriptor <dynamic> searchDescriptor)
 {
     return(searchDescriptor.Highlight(h => h.PreTags("<b>").PostTags("</b>").Fields(fs => fs.Field("*").NumberOfFragments(0))));
 }