Beispiel #1
0
        public static List <SearchVm2> Query(string keyWord, int rowNum, int count)
        {
            //定义solr
            //ISolrOperations<SearchVm2> solr= ServiceLocator.Current.GetInstance<ISolrOperations<SearchVm2>>();

            //建立排序,条件.
            QueryOptions options = new QueryOptions();

            options.Rows  = count; //数据条数
            options.Start = 1;     //开始项


            //创建查询条件
            var qTB = new SolrQueryByField("text", keyWord);

            //创建条件集合
            List <ISolrQuery> query = new List <ISolrQuery>();

            //添加条件
            query.Add(qTB);

            //按照时间倒排序.
            options.AddOrder(new SortOrder("CreateTime", Order.DESC));

            //条件集合之间的关系
            var qTBO = new SolrMultipleCriteriaQuery(query, "OR");

            //执行查询,有5个重载
            //SolrQueryResults<SearchVm2> results = solr.Query(qTBO,options);


            return(null);//results;
        }
        internal SolrQueryResults <Dictionary <string, object> > Execute(SolrCompositeQuery compositeQuery, Type resultType)
        {
            var options = new QueryOptions();

            if (compositeQuery.Methods != null)
            {
                var list1 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Select).Select(m => (SelectMethod)m).ToList();
                if (list1.Any())
                {
                    foreach (
                        var str in
                        list1.SelectMany(selectMethod => (IEnumerable <string>)selectMethod.FieldNames))
                    {
                        options.Fields.Add(str.ToLowerInvariant());
                    }
                    options.Fields.Add("_uniqueid");
                    options.Fields.Add("_datasource");
                }
                var list2 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.GetResults).Select(m => (GetResultsMethod)m).ToList();
                if (list2.Any())
                {
                    if (options.Fields.Count > 0)
                    {
                        options.Fields.Add("score");
                    }
                    else
                    {
                        options.Fields.Add("*");
                        options.Fields.Add("score");
                    }
                }
                var list3 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.OrderBy).Select(m => (OrderByMethod)m).ToList();
                if (list3.Any())
                {
                    foreach (var orderByMethod in list3)
                    {
                        var field = orderByMethod.Field;
                        options.AddOrder(new SortOrder(field,
                                                       orderByMethod.SortDirection == SortDirection.Ascending ? Order.ASC : Order.DESC));
                    }
                }
                int startIdx;
                int maxHits;
                this.GetMaxHits(compositeQuery, this._contentSearchSettings.SearchMaxResults(), out startIdx, out maxHits);
                var list4 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Skip).Select(m => (SkipMethod)m).ToList();
                if (list4.Any())
                {
                    var num = list4.Sum(skipMethod => skipMethod.Count);
                    options.Start = new int?(num);
                }
                var list5 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Take).Select(m => (TakeMethod)m).ToList();
                if (list5.Any())
                {
                    var num = list5.Sum(takeMethod => takeMethod.Count);
                    options.Rows = new int?(num);
                }
                var list6 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Count).Select(m => (CountMethod)m).ToList();
                if (compositeQuery.Methods.Count == 1 && list6.Any())
                {
                    options.Rows = new int?(0);
                }
                var list7 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Any).Select(m => (AnyMethod)m).ToList();
                if (compositeQuery.Methods.Count == 1 && list7.Any())
                {
                    options.Rows = new int?(0);
                }
                var list8 =
                    compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.GetFacets).Select(m => (GetFacetsMethod)m).ToList();
                if (compositeQuery.FacetQueries.Count > 0 &&
                    (list8.Any() ||
                     list2.Any()))
                {
                    foreach (
                        var facetQuery in
                        GetFacetsPipeline.Run(
                            new GetFacetsArgs(null,
                                              compositeQuery.FacetQueries, this._context.Index.Configuration.VirtualFieldProcessors, this._context.Index.FieldNameTranslator)).FacetQueries.ToHashSet())
                    {
                        if (facetQuery.FieldNames.Any())
                        {
                            var minimumResultCount = facetQuery.MinimumResultCount;

                            if (facetQuery.FieldNames.Count() == 1)
                            {
                                var fieldNameTranslator = this.FieldNameTranslator as SolrFieldNameTranslator;

                                var fieldName = facetQuery.FieldNames.First();

                                if (fieldNameTranslator != null &&
                                    fieldName == fieldNameTranslator.StripKnownExtensions(fieldName) &&
                                    this._context.Index.Configuration.FieldMap.GetFieldConfiguration(fieldName) == null)
                                {
                                    fieldName =
                                        fieldNameTranslator.GetIndexFieldName(
                                            fieldName.Replace("__", "!").Replace("_", " ").Replace("!", "__"), true);
                                }

                                /**
                                 * ******* UPDATED HERE *******
                                 * If any FilterValues passed into the Facets, add them to the FilterValues AND the Facet On
                                 * have them excluded
                                 */
                                if (facetQuery.FilterValues.Any())
                                {
                                    options.AddFilterQueries(new LocalParams {
                                        { "tag", fieldName }
                                    } +new SolrQueryInList(fieldName, facetQuery.FilterValues.Cast <string>()));

                                    options.AddFacets(
                                        new SolrFacetFieldQuery(new LocalParams {
                                        { "ex", fieldName }
                                    } +fieldName));
                                }
                                else
                                {
                                    options.AddFacets((ISolrFacetQuery) new SolrFacetFieldQuery(fieldName)
                                    {
                                        MinCount = minimumResultCount
                                    });
                                }
                            }

                            if (facetQuery.FieldNames.Count() > 1)
                            {
                                options.AddFacets((ISolrFacetQuery) new SolrFacetPivotQuery()
                                {
                                    Fields = (ICollection <string>) new string[1]
                                    {
                                        string.Join(",", facetQuery.FieldNames)
                                    },
                                    MinCount = minimumResultCount
                                });
                            }
                        }
                    }
                    if (!list2.Any())
                    {
                        options.Rows = new int?(0);
                    }
                }
            }
            if (compositeQuery.Filter != null)
            {
                options.AddFilterQueries((ISolrQuery)compositeQuery.Filter);
            }
            options.AddFilterQueries((ISolrQuery) new SolrQueryByField("_indexname", this._context.Index.Name));
            if (!this._settings.DefaultLanguage().StartsWith(this._cultureCode))
            {
                options.AddFilterQueries((ISolrQuery) new SolrQueryByField("_language", this._cultureCode + "*")
                {
                    Quoted = false
                });
            }
            var loggingSerializer = new SolrLoggingSerializer();
            var q = loggingSerializer.SerializeQuery(compositeQuery.Query);
            var solrSearchIndex = this._context.Index as SolrSearchIndex;

            try
            {
                if (!options.Rows.HasValue)
                {
                    options.Rows = new int?(this._contentSearchSettings.SearchMaxResults());
                }
                SearchLog.Log.Info("Query - " + q, null);
                SearchLog.Log.Info(
                    "Serialized Query - ?q=" + q + "&" +
                    string.Join("&",
                                loggingSerializer.GetAllParameters(options).Select(p => string.Format("{0}={1}", p.Key, p.Value)).ToArray()),
                    null);
                return(this.SolrOperations.Query(q, options));
            }
            catch (Exception ex)
            {
                if (!(ex is SolrConnectionException) && !(ex is SolrNetException))
                {
                    throw;
                }
                else
                {
                    var message = ex.Message;
                    if (ex.Message.StartsWith("<?xml"))
                    {
                        var xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(ex.Message);
                        var xmlNode1 =
                            xmlDocument.SelectSingleNode("/response/lst[@name='error'][1]/str[@name='msg'][1]");
                        var xmlNode2 =
                            xmlDocument.SelectSingleNode(
                                "/response/lst[@name='responseHeader'][1]/lst[@name='params'][1]/str[@name='q'][1]");
                        if (xmlNode1 != null && xmlNode2 != null)
                        {
                            SearchLog.Log.Error(
                                string.Format("Solr Error : [\"{0}\"] - Query attempted: [{1}]",
                                              xmlNode1.InnerText, xmlNode2.InnerText), null);
                            return(new SolrQueryResults <Dictionary <string, object> >());
                        }
                    }
                    Log.Error(message, this);
                    return(new SolrQueryResults <Dictionary <string, object> >());
                }
            }
        }
        internal SolrQueryResults <Dictionary <string, object> > Execute(SolrCompositeQuery compositeQuery, Type resultType)
        {
            var queryOpertions = new QueryOptions();

            if (compositeQuery.Methods != null)
            {
                var selectFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Select).Select(m => (SelectMethod)m).ToList();

                if (selectFields.Any())
                {
                    foreach (var fieldName in selectFields.SelectMany(selectMethod => selectMethod.FieldNames))
                    {
                        queryOpertions.Fields.Add(fieldName.ToLowerInvariant());
                    }

                    if (!this.context.SecurityOptions.HasFlag(SearchSecurityOptions.DisableSecurityCheck))
                    {
                        queryOpertions.Fields.Add(BuiltinFields.UniqueId);
                        queryOpertions.Fields.Add(BuiltinFields.DataSource);
                    }
                }

                var getResultsFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.GetResults).Select(m => (GetResultsMethod)m).ToList();

                if (getResultsFields.Any())
                {
                    if (queryOpertions.Fields.Count > 0)
                    {
                        queryOpertions.Fields.Add("score");
                    }
                    else
                    {
                        queryOpertions.Fields.Add("*");
                        queryOpertions.Fields.Add("score");
                    }
                }

                var sortFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.OrderBy).Select(m => ((OrderByMethod)m)).ToList();

                if (sortFields.Any())
                {
                    foreach (var sortField in sortFields)
                    {
                        var fieldName = sortField.Field;
                        queryOpertions.AddOrder(new SortOrder(fieldName, sortField.SortDirection == SortDirection.Ascending ? Order.ASC : Order.DESC));
                    }
                }

                var skipFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Skip).Select(m => (SkipMethod)m).ToList();

                if (skipFields.Any())
                {
                    var start = skipFields.Sum(skipMethod => skipMethod.Count);
                    queryOpertions.Start = start;
                }

                var takeFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Take).Select(m => (TakeMethod)m).ToList();

                if (takeFields.Any())
                {
                    var rows = takeFields.Sum(takeMethod => takeMethod.Count);
                    queryOpertions.Rows = rows;
                }

                var countFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Count).Select(m => (CountMethod)m).ToList();

                if (compositeQuery.Methods.Count == 1 && countFields.Any())
                {
                    queryOpertions.Rows = 0;
                }

                var anyFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.Any).Select(m => (AnyMethod)m).ToList();

                if (compositeQuery.Methods.Count == 1 && anyFields.Any())
                {
                    queryOpertions.Rows = 0;
                }

                var facetFields = compositeQuery.Methods.Where(m => m.MethodType == QueryMethodType.GetFacets).Select(m => (GetFacetsMethod)m).ToList();

                if (compositeQuery.FacetQueries.Count > 0 && (facetFields.Any() || getResultsFields.Any()))
                {
                    var result       = GetFacetsPipeline.Run(this.pipeline, new GetFacetsArgs(null, compositeQuery.FacetQueries, this.context.Index.Configuration.VirtualFieldProcessors, this.context.Index.FieldNameTranslator));
                    var facetQueries = result.FacetQueries.ToHashSet();

                    foreach (var facetQuery in facetQueries)
                    {
                        if (!facetQuery.FieldNames.Any())
                        {
                            continue;
                        }

                        var minCount = facetQuery.MinimumResultCount;

                        if (facetQuery.FieldNames.Count() == 1)
                        {
                            var fn        = FieldNameTranslator as SolrFieldNameTranslator;
                            var fieldName = facetQuery.FieldNames.First();

                            if (fn != null && fieldName == fn.StripKnownExtensions(fieldName) && this.context.Index.Configuration.FieldMap.GetFieldConfiguration(fieldName) == null)
                            {
                                fieldName = fn.GetIndexFieldName(fieldName.Replace("__", "!").Replace("_", " ").Replace("!", "__"), true);
                            }

                            queryOpertions.AddFacets(new SolrFacetFieldQuery(fieldName)
                            {
                                MinCount = minCount
                            });
                        }

                        if (facetQuery.FieldNames.Count() > 1)
                        {
                            queryOpertions.AddFacets(new SolrFacetPivotQuery {
                                Fields = new[] { string.Join(",", facetQuery.FieldNames) }, MinCount = minCount
                            });
                        }
                    }

                    if (!getResultsFields.Any())
                    {
                        queryOpertions.Rows = 0;
                    }
                }
            }

            if (compositeQuery.Filter != null)
            {
                queryOpertions.AddFilterQueries(compositeQuery.Filter);
            }

            queryOpertions.AddFilterQueries(new SolrQueryByField(BuiltinFields.IndexName, this.context.Index.Name));

            if (!Settings.DefaultLanguage.StartsWith(this.cultureCode))
            {
                queryOpertions.AddFilterQueries(new SolrQueryByField(BuiltinFields.Language, this.cultureCode + "*")
                {
                    Quoted = false
                });
            }

            var querySerializer = new SolrLoggingSerializer();
            var serializedQuery = querySerializer.SerializeQuery(compositeQuery.Query);

            var idx = this.context.Index as SolrSearchIndex;

            PrepareHiglightOptions(compositeQuery, queryOpertions);

            try
            {
                if (queryOpertions.Rows == null)
                {
                    queryOpertions.Rows = this.contentSearchSettings.SearchMaxResults();
                }

                SearchLog.Log.Info("Query - " + serializedQuery);
                SearchLog.Log.Info("Serialized Query - " + "?q=" + serializedQuery + "&" + string.Join("&", querySerializer.GetAllParameters(queryOpertions).Select(p => string.Format("{0}={1}", p.Key, p.Value)).ToArray()));

                return(GetOperations(idx).Query(serializedQuery, queryOpertions));
            }
            catch (Exception exception)
            {
                if (!(exception is SolrConnectionException) && !(exception is SolrNetException))
                {
                    throw;
                }

                var message = exception.Message;

                if (exception.Message.StartsWith("<?xml"))
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(exception.Message);
                    var errorNode = doc.SelectSingleNode("/response/lst[@name='error'][1]/str[@name='msg'][1]");
                    var queryNode = doc.SelectSingleNode("/response/lst[@name='responseHeader'][1]/lst[@name='params'][1]/str[@name='q'][1]");
                    if (errorNode != null && queryNode != null)
                    {
                        message = string.Format("Solr Error : [\"{0}\"] - Query attempted: [{1}]", errorNode.InnerText, queryNode.InnerText);
                        SearchLog.Log.Error(message);
                        return(new SolrQueryResults <Dictionary <string, object> >());
                    }
                }

                Log.Error(message, this);
                return(new SolrQueryResults <Dictionary <string, object> >());
            }
        }
Beispiel #4
0
        /// <summary>
        /// 根据搜索关键词和排序、筛选条件获取(第N页数据)检索数据
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="sort">排序条件:1.新品排序 2.价格升序 3.价格降序 4.折扣升序</param>
        /// <param name="brands">筛选品牌:e.g. ["华为","小米","iphone"]</param>
        /// <returns>检索结果集合</returns>
        public SolrQueryResults <ProductSearchModel> GetProductListByOptionsAndPageIndex(string keyword, int sort, string brands, int pageIndex, int pageSize)
        {
            //创建solr对象
            ISolrOperations <ProductSearchModel> solr = ServiceLocator.Current.GetInstance <ISolrOperations <ProductSearchModel> >();

            //判断参数是否为空or所有
            if (!string.IsNullOrEmpty(keyword) && keyword.Trim() != "*")
            {
                keyword = keyword.Trim().Replace(@"\", " ");
                keyword = StringVerify.StringToPattern(keyword);//转义这些Solr特殊字符 + - && || ! ( ) { } [ ] ^ ” ~ * ? : \
                //string[] keywords = keyword.Split(' ');
                //创建条件集合
                QueryOptions options = new QueryOptions();
                options.Rows  = pageSize;
                options.Start = pageSize * (pageIndex - 1);

                List <ISolrQuery> query = new List <ISolrQuery>();

                //构建OR关系条件
                List <ISolrQuery> keyOr = new List <ISolrQuery>();
                //if (keywords.Length > 0)
                //{
                //    foreach (var k in keywords)
                //    {
                //        if (!string.IsNullOrEmpty(k.Trim()))
                //        {
                //            keyOr.Add(new SolrQuery("Name_IK:" + k));
                //            keyOr.Add(new SolrQuery("searchText:" + k));
                //        }
                //    }
                //}
                //else
                //{
                //    keyword=keyword.Replace(" ", "");
                //    keyOr.Add(new SolrQuery("Name_IK:" +keywords));
                //    keyOr.Add(new SolrQuery("searchText:" + keywords));
                //}

                keyOr.Add(new SolrQuery("Name_IK:" + keyword));
                keyOr.Add(new SolrQuery("searchText:" + keyword));
                var ko = new SolrMultipleCriteriaQuery(keyOr, "OR");
                query.Add(ko);

                //排序条件
                switch (sort)
                {
                case 1:
                    //设定查询结果的排序,按照上架时间降序.[2016.7.20修改需求,上新排序改为默认的权重排序]
                    //options.AddOrder(new SolrNet.SortOrder("OnSaleTime", SolrNet.Order.DESC));
                    break;

                case 2:
                    //按照打折后的价格升序.
                    options.AddOrder(new SolrNet.SortOrder("DiscountPrice", SolrNet.Order.ASC));
                    break;

                case 3:
                    //按照打折后的价格降序.
                    options.AddOrder(new SolrNet.SortOrder("DiscountPrice", SolrNet.Order.DESC));
                    break;

                case 4:
                    //按照折扣升序.(1折、2折、3折...10折)
                    options.AddOrder(new SolrNet.SortOrder("DiscountRate", SolrNet.Order.ASC));
                    break;

                default:
                    break;
                }
                //品牌筛选
                SolrQueryResults <ProductSearchModel> products;
                if (brands != "")
                {
                    var blist = JsonHelper.ToObject <List <string> >(brands);
                    //品牌筛选(&&操作)由于传过来的值肯定都是完整的品牌名称
                    //所以不用去Brand_IK中检索,而是直接去Brank中匹配
                    //构建OR关系条件
                    List <ISolrQuery> brandOr = new List <ISolrQuery>();
                    for (int i = 0; i < blist.Count; i++)
                    {
                        blist[i] = StringVerify.StringToPattern(blist[i]);//转义这些Solr特殊字符 + - && || ! ( ) { } [ ] ^ ” ~ * ? : \
                        brandOr.Add(new SolrQuery("Brand:" + blist[i]));
                    }
                    //foreach (var brand in blist)
                    //{
                    //    brandOr.Add(new SolrQuery("Brand:" + brand));
                    //}
                    var bo = new SolrMultipleCriteriaQuery(brandOr, "OR");
                    query.Add(bo);

                    //最终跟Query主条件进行构建 AND 关系条件
                    var querys = new SolrMultipleCriteriaQuery(query, "AND");
                    products = solr.Query(querys, options);
                }
                else
                {
                    //输入关键词,检索数据,顺便给品牌分组,返回品牌数组
                    var facet = new FacetParameters
                    {
                        Queries = new[] { new SolrFacetFieldQuery("Brand") }
                    };
                    options.Facet = facet;
                    products      = solr.Query(ko, options);
                }
                return(products);
            }
            return(null);
        }