internal static void AddDateRangeQuery(BooleanQuery query, DateRangeSearchParam.DateRangeField dateRangeField, BooleanClause.Occur occurance)
        {
            var startDateTime = dateRangeField.StartDate;
            if (dateRangeField.InclusiveStart)
            {
                if (startDateTime != DateTime.MinValue)
                {
                    startDateTime.ChangeTime(0, 0, 0, 0);
                }
            }

            var endDateTime = dateRangeField.EndDate;
            if (dateRangeField.InclusiveStart)
            {
                if (endDateTime != DateTime.MaxValue)
                {
                    endDateTime = endDateTime.ChangeTime(23, 59, 59, 59);
                }
            }

            BooleanQuery.SetMaxClauseCount(int.MaxValue);

            if (!(dateRangeField.StartDate == DateTime.MinValue && dateRangeField.EndDate == DateTime.MaxValue))
            {
                query.Add(new RangeQuery(new Term(SearchFieldIDs.CreatedDate, startDateTime.ToString("yyyyMMdd")), new Term(SearchFieldIDs.CreatedDate, endDateTime.ToString("yyyyMMdd")), true), occurance);
            }
        }
        /// <summary>
        /// Get Items to be loaded when the Control is loaded on the item
        /// </summary>
        /// <param name="current">
        /// The current.
        /// </param>
        /// <returns>
        /// Array of Item
        /// </returns>
        protected override Item[] GetItems(Item current)
        {
            Assert.ArgumentNotNull(current, "current");
            var values = StringUtil.GetNameValues(Source, '=', '&');
            var refinements = new SafeDictionary<string>();
            if (values["FieldsFilter"] != null)
            {
                var splittedFields = StringUtil.GetNameValues(values["FieldsFilter"], ':', ',');
                foreach (string key in splittedFields.Keys)
                {
                    refinements.Add(key, splittedFields[key]);
                }
            }

            var locationFilter = values["StartSearchLocation"];
            locationFilter = MakeFilterQuerable(locationFilter);

            var templateFilter = values["TemplateFilter"];
            templateFilter = MakeTemplateFilterQuerable(templateFilter);

            var pageSize = values["PageSize"];
            var searchParam = new DateRangeSearchParam
            {
                Refinements = refinements,
                LocationIds = locationFilter.IsNullOrEmpty() ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).GetParentBucketItemOrRootOrSelf().ID.ToString() : locationFilter,
                TemplateIds = templateFilter,
                FullTextQuery = values["FullTextQuery"],
                Language = values["Language"],
                PageSize = pageSize.IsEmpty() ? 10 : int.Parse(pageSize),
                PageNumber = this.pageNumber,
                SortByField = values["SortField"],
                SortDirection = values["SortDirection"]
            };

            this.filter = "&location=" + (locationFilter.IsNullOrEmpty() ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).GetParentBucketItemOrRootOrSelf().ID.ToString() : locationFilter) +
                     "&filterText=" + values["FullTextQuery"] +
                     "&language=" + values["Language"] +
                     "&pageSize=" + (pageSize.IsEmpty() ? 10 : int.Parse(pageSize)) +
                     "&sort=" + values["SortField"];

            if (values["TemplateFilter"].IsNotNull())
            {
                this.filter += "&template=" + templateFilter;
            }

            using (var searcher = new IndexSearcher(Constants.Index.Name))
            {
                var keyValuePair = searcher.GetItems(searchParam);
                var items = keyValuePair.Value;
                this.pageNumber = keyValuePair.Key / searchParam.PageSize;
                if (this.pageNumber <= 0)
                {
                    this.pageNumber = 1;
                }
                return items.Select(sitecoreItem => sitecoreItem.GetItem()).Where(i => i != null).ToArray();
            }
        }
        /// <summary>
        /// An extension of Item that allows you to launch a Search from an item
        /// </summary>
        /// <returns>List of Results of Type IEnumerable List of SitecoreItem (which implements IItem)</returns>
        /// <param name="startLocationItem">The start location of the search</param>
        /// <param name="refinements">A collection of refinements to the query</param>
        /// <param name="hitCount">This will output the hitCount of the search</param>
        /// <param name="relatedIds">Pipe delimited string of Id to query by Links to and from items</param>
        /// <param name="indexName">Force query to run on a particular index</param>
        /// <param name="text">The raw text query</param>
        /// <param name="templates">Pipe delimited string of Id of Templates</param>
        /// <param name="location">Override the location of the search with an Id</param>
        /// <param name="language">Query by the two letter ISO country code</param>
        /// <param name="id">Query by ID</param>
        /// <param name="sortField">Sort query by field (must be in index)</param>
        /// <param name="sortDirection">Sort in either "asc" or "desc"</param>
        /// <param name="itemName">Query by item name</param>
        /// <param name="startDate">mm/dd/yyyy format of start date</param>
        /// <param name="endDate">mm/dd/yyyy format of end date</param>
        /// <param name="numberOfItemsToReturn">0-XXXXXX (The bigger this number is the less performant it will be)</param>
        /// <example>BucketManager.Search(Sitecore.Context.Item, text: "Tim", templates: "TemplateGUID")</example>
        /// <example>BucketManager.Search(Sitecore.Context.Item, text: "Tim", relatedIds: "ItemGUID", sortField: "_name")</example>
        public static IEnumerable<SitecoreItem> Search(Item startLocationItem, SafeDictionary<string> refinements, out int hitCount, IEnumerable<Guid> relatedIds = null, string indexName = "itembuckets_buckets", string text = "", IEnumerable<Guid> templates = null, string location = "", string language = "en", string id = "", string sortField = "", string sortDirection = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20)
        {
            using (var searcher = new IndexSearcher(indexName))
            {
                var culture = CultureInfo.CreateSpecificCulture("en-US");
                var startDateOut = DateTime.Now;
                var endDateOut = DateTime.Now.AddDays(1);
                var startFlag = true;
                var endFlag = true;
                if (!DateTime.TryParse(startDate, culture, DateTimeStyles.None, out startDateOut))
                {
                    startDateOut = DateTime.Now;
                    startFlag = false;
                }

                if (!DateTime.TryParse(endDate, culture, DateTimeStyles.None, out endDateOut))
                {
                    endDateOut = DateTime.Now.AddDays(1);
                    endFlag = false;
                }

                if (startLocationItem.IsNull())
                {
                    Log.Warn("You are trying to run an Search on an item that has a start location of null", null);
                    hitCount = 0;
                    return new List<SitecoreItem>();
                }

                var dateSearchParam = new DateRangeSearchParam
                                          {
                                              ItemName = itemName,
                                              FullTextQuery = text,
                                              RelatedIds = relatedIds,
                                              TemplateIds = templates,
                                              LocationIds = startLocationItem.ID.ToGuid().ToEnumerable(),
                                              Language = language,
                                              SortDirection = sortDirection,
                                              Refinements = refinements,
                                              ID = id,
                                              SortByField = sortField,
                                              PageSize = numberOfItemsToReturn
                                          };

                if (startFlag || endFlag)
                {
                    dateSearchParam.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                                 {
                                                     new DateRangeSearchParam.DateRangeField(
                                                         SearchFieldIDs.CreatedDate,
                                                         startDateOut,
                                                         endDateOut)
                                                         {
                                                             InclusiveStart = true, InclusiveEnd = true
                                                         }
                                                 };
                }

                var keyValuePair = searcher.GetItems(dateSearchParam);
                hitCount = keyValuePair.Key;
                return keyValuePair.Value;
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <param name="itm">
        /// The itm.
        /// </param>
        /// <param name="currentSearchString">
        /// The current Search String.
        /// </param>
        /// <param name="hitCount">
        /// The hit Count.
        /// </param>
        /// <param name="indexName">
        /// The index Name.
        /// </param>
        /// <param name="sortField">
        /// The sort Field.
        /// </param>
        /// <param name="sortDirection">
        /// The sort Direction.
        /// </param>
        /// <param name="pageSize">
        /// The page Size.
        /// </param>
        /// <param name="pageNumber">
        /// The page Number.
        /// </param>
        /// <param name="parameters">
        /// The parameters.
        /// </param>
        /// <returns>
        /// IEnumreable List of Results that have been typed to a smaller version of the Item Object
        /// </returns>
        public static IEnumerable<SitecoreItem> FullSearch(Item itm, List<SearchStringModel> currentSearchString, out int hitCount, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "", int pageSize = 0, int pageNumber = 0, object[] parameters = null)
        {
            var startDate = DateTime.Now;
            var endDate = DateTime.Now.AddDays(1);
            var locationSearch = LocationFilter;
            var refinements = new SafeDictionary<string>();
            var searchStringModels = SearchHelper.GetTags(currentSearchString);

            if (searchStringModels.Count > 0)
            {
                foreach (var ss in searchStringModels)
                {
                    var query = ss.Value;
                    if (query.Contains("tagid="))
                    {
                        query = query.Split('|')[1].Replace("tagid=", string.Empty);
                    }
                    var db = Context.ContentDatabase ?? Context.Database;
                    refinements.Add("_tags", db.GetItem(query).ID.ToString());
                }
            }

            var author = SearchHelper.GetAuthor(currentSearchString);

            var languages = SearchHelper.GetLanguages(currentSearchString);
            if (languages.Length > 0)
            {
                refinements.Add("_language", languages);
            }

            var references = SearchHelper.GetReferences(currentSearchString);

            var custom = SearchHelper.GetCustom(currentSearchString);
            if (custom.Length > 0)
            {
                var customSearch = custom.Split('|');
                if (customSearch.Length > 0)
                {
                    try
                    {
                        refinements.Add(customSearch[0], customSearch[1]);
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Could not parse the custom search query", exc);
                    }
                }
            }

            var search = SearchHelper.GetField(currentSearchString);
            if (search.Length > 0)
            {
                var customSearch = search;
                refinements.Add(customSearch, SearchHelper.GetText(currentSearchString));
            }

            var fileTypes = SearchHelper.GetFileTypes(currentSearchString);
            if (fileTypes.Length > 0)
            {
                refinements.Add("extension", SearchHelper.GetFileTypes(currentSearchString));
            }

            var s = SearchHelper.GetSite(currentSearchString);
            if (s.Length > 0)
            {
                SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name);
                var db = Context.ContentDatabase ?? Context.Database;
                var startItemId = db.GetItem(siteContext.StartPath);
                locationSearch = startItemId.ID.ToString();
            }

            var culture = CultureInfo.CreateSpecificCulture("en-US");
            var startFlag = true;
            var endFlag = true;
            if (SearchHelper.GetStartDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetStartDate(currentSearchString), culture, DateTimeStyles.None, out startDate))
                {
                    startDate = DateTime.Now;
                }

                startFlag = false;
            }

            if (SearchHelper.GetEndDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetEndDate(currentSearchString), culture, DateTimeStyles.None, out endDate))
                {
                    endDate = DateTime.Now.AddDays(1);
                }

                endFlag = false;
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var location = IdHelper.ParseId(SearchHelper.GetLocation(currentSearchString, locationSearch));
                var locationIdFromItem = itm != null ? itm.ID.ToGuid().ToEnumerable() : null;
                var rangeSearch = new DateRangeSearchParam
                {
                    ID = SearchHelper.GetID(currentSearchString).IsEmpty() ? SearchHelper.GetRecent(currentSearchString) : SearchHelper.GetID(currentSearchString),
                    ShowAllVersions = false,
                    FullTextQuery = SearchHelper.GetText(currentSearchString),
                    Refinements = refinements,
                    RelatedIds = references.Any() ? IdHelper.ParseId(references) : null,
                    SortDirection = sortDirection,
                    TemplateIds = SearchHelper.GetTemplates(currentSearchString),
                    LocationIds = !location.Any() ? locationIdFromItem : location,
                    Language = languages,
                    SortByField = sortField,
                    PageNumber = pageNumber,
                    PageSize = pageSize,
                    Author = author == string.Empty ? string.Empty : author,
                };

                if (!startFlag || !endFlag)
                {
                    rangeSearch.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                             {
                                                 new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate)
                                                     {
                                                         InclusiveStart = true, InclusiveEnd = true
                                                     }
                                             };
                }

                var returnResult = searcher.GetItems(rangeSearch);
                hitCount = returnResult.Key;
                return returnResult.Value;
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumreable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable<SitecoreItem> Search(this Item itm, out int hitCount, string relatedIds = "", string indexName = "itembuckets_buckets", string text = "", string templates = "", string location = "", string sortDirection = "", string language = "en", string id = "", string sortField = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20, int pageNumber = 0)
        {
            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                                          {
                                              ItemName = itemName,
                                              FullTextQuery = text,
                                              RelatedIds = relatedIds,
                                              TemplateIds = templates,
                                              LocationIds = location.IsEmpty() ? itm.ID.ToString() : location,
                                              Language = language,
                                              ID = id,
                                              SortDirection = sortDirection,
                                              SortByField = sortField,
                                              PageSize = numberOfItemsToReturn,
                                              PageNumber = pageNumber,
                                              Ranges = SearchHelper.GetDateRefinements(startDate,endDate)
                                          };
                var keyValuePair = searcher.GetItems(dateSearchParam);

                hitCount = keyValuePair.Key;
                return keyValuePair.Value;
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumerable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable<SitecoreItem> Search(this Item itm, SafeDictionary<string> refinements, out int hitCount,
            string relatedIds = "",
            string indexName = "itembuckets_buckets", 
            string text = "", 
            string templates = "", 
            string location = "", 
            string language = "en", 
            string id = "", 
            string sortField = "", 
            string itemName = "", 
            string startDate = "",
            int pageNumber = 0,
            string endDate = "", 
            string sortDirection = "",
            int numberOfItemsToReturn = 20, 
            object[] parameters = null)
        {
            if (itm.IsNull())
            {
                Log.Warn("You are trying to run an Item Extension on an item that is null", "");
                hitCount = 0;
                return new List<SitecoreItem>();
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                                          {
                                              ItemName = itemName,
                                              FullTextQuery = text,
                                              RelatedIds = relatedIds,
                                              TemplateIds = templates,
                                              LocationIds = location.IsEmpty() ? itm.ID.ToString() : location,
                                              Language = language,
                                              SortDirection = sortDirection,
                                              Refinements = refinements,
                                              ID = id,
                                              SortByField = sortField,
                                              PageSize = numberOfItemsToReturn,
                                              PageNumber = pageNumber,
                                              Ranges = SearchHelper.GetDateRefinements(startDate, endDate)
                                          };
                var keyValuePair = searcher.GetItems(dateSearchParam);
                hitCount = keyValuePair.Key;
                return keyValuePair.Value;
            }
        }
示例#7
0
        public static BooleanQuery ContructQuery(DateRangeSearchParam param)
        {
            var indexName = BucketManager.GetContextIndex(Context.ContentDatabase.GetItem(param.LocationIds));

            if (indexName.EndsWith("_remote"))
            {
                Index = RemoteSearchManager.GetIndex(indexName) as RemoteIndex;
            }
            else if (indexName.EndsWith("_inmemory"))
            {
                Index = InMemorySearchManager.GetIndex(indexName) as InMemoryIndex;
            }
            else
            {
                Index = SearchManager.GetIndex(indexName) as Index;
            }
            if (Index.IsNotNull())
            {
                var globalQuery = new CombinedQuery();
                var fullTextQuery = param.FullTextQuery; // .TrimStart('*').TrimEnd('*') + "*";
                SearcherMethods.ApplyLanguageClause(globalQuery, param.Language);
                if (!string.IsNullOrWhiteSpace(fullTextQuery))
                {
                    if (!fullTextQuery.StartsWith("*"))
                    {
                        SearcherMethods.ApplyFullTextClause(globalQuery, fullTextQuery, indexName);
                    }
                }

                SearcherMethods.ApplyRelationFilter(globalQuery, param.RelatedIds);
                SearcherMethods.ApplyTemplateFilter(globalQuery, param.TemplateIds);
                SearcherMethods.ApplyTemplateNotFilter(globalQuery);
                SearcherMethods.ApplyIDFilter(globalQuery, param.ID);
                SearcherMethods.ApplyLocationFilter(globalQuery, param.LocationIds);
                SearcherMethods.ApplyRefinements(globalQuery, param.Refinements, QueryOccurance.Should);
                SearcherMethods.ApplyLatestVersion(globalQuery);

                if (Config.ExcludeContextItemFromResult)
                {
                    SearcherMethods.ApplyContextItemRemoval(globalQuery, param.LocationIds);
                }

                var translator = new QueryTranslator(Index);
                var booleanQuery = translator.ConvertCombinedQuery(globalQuery);
                var innerOccurance = translator.GetOccur(param.Occurance);

                if (!string.IsNullOrWhiteSpace(fullTextQuery))
                {
                    if (fullTextQuery.StartsWith("*"))
                    {
                        SearcherMethods.ApplyFullTextClause(booleanQuery, fullTextQuery, indexName);
                    }
                }

                SearcherMethods.ApplyAuthor(booleanQuery, param.Author);
                SearcherMethods.ApplyDateRangeSearchParam(booleanQuery, param, innerOccurance);
                if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug)
                {
                    Log.Info("Search Clauses Number: " + booleanQuery.Clauses().Count, booleanQuery);
                }

                return booleanQuery;
            }

            return null;
        }
示例#8
0
        internal virtual KeyValuePair<int, List<SitecoreItem>> GetItems(DateRangeSearchParam param)
        {
            var db = Context.ContentDatabase ?? Sitecore.Context.Database;
            if (db != null)
            {
                var indexName = Util.Constants.Index.Name;
                var item = db.GetItem(param.LocationIds);
                indexName = BucketManager.GetContextIndex(item.IsNotNull() ? item : db.GetItem(Sitecore.ItemIDs.RootID));

                if (indexName.EndsWith("_remote"))
                {
                    Index = RemoteSearchManager.GetIndex(indexName) as RemoteIndex;
                }
                else if (indexName.EndsWith("_inmemory"))
                {
                    Index = InMemorySearchManager.GetIndex(indexName) as InMemoryIndex;
                }
                else
                {
                    Index = SearchManager.GetIndex(indexName) as Index;
                }

                if (Index.IsNotNull())
                {
                    var globalQuery = new CombinedQuery();
                    SearcherMethods.ApplyLanguageClause(globalQuery, param.Language);
                    if (!string.IsNullOrWhiteSpace(param.FullTextQuery))
                    {
                        if (!param.FullTextQuery.StartsWith("*"))
                        {
                            if (param.FullTextQuery != "*All*" && param.FullTextQuery != "*" && param.FullTextQuery != "**")
                            {
                                SearcherMethods.ApplyFullTextClause(globalQuery, param.FullTextQuery, indexName);
                            }
                        }
                    }

                    SearcherMethods.ApplyRelationFilter(globalQuery, param.RelatedIds);
                    SearcherMethods.ApplyTemplateFilter(globalQuery, param.TemplateIds);
                    SearcherMethods.ApplyTemplateNotFilter(globalQuery);
                    SearcherMethods.ApplyIDFilter(globalQuery, param.ID);
                    if (param.LocationIds.Contains("|"))
                    {
                        SearcherMethods.ApplyCombinedLocationFilter(globalQuery, param.LocationIds);
                    }
                    else
                    {
                        SearcherMethods.ApplyLocationFilter(globalQuery, param.LocationIds);
                    }
                    if (!param.Refinements.ContainsKey("__workflow state")) //Hack!!!!!
                    {
                        SearcherMethods.ApplyRefinements(globalQuery, param.Refinements, QueryOccurance.Should);
                    }
                    SearcherMethods.ApplyLatestVersion(globalQuery);

                    if (Config.ExcludeContextItemFromResult)
                    {
                        SearcherMethods.ApplyContextItemRemoval(globalQuery, param.LocationIds);
                    }
                    SearcherMethods.ApplyNameFilter(globalQuery, param.ItemName);
                    var translator = new QueryTranslator(Index);
                    var booleanQuery = translator.ConvertCombinedQuery(globalQuery);
                    var innerOccurance = translator.GetOccur(param.Occurance);

                    if (!string.IsNullOrWhiteSpace(param.FullTextQuery))
                    {
                        if (param.FullTextQuery.StartsWith("*"))
                        {
                            if (param.FullTextQuery != "*All*" && param.FullTextQuery != "*" && param.FullTextQuery != "**")
                            {
                                SearcherMethods.ApplyFullTextClause(booleanQuery, param.FullTextQuery, indexName);
                            }
                        }
                    }

                    SearcherMethods.ApplyAuthor(booleanQuery, param.Author);
                    SearcherMethods.ApplyDateRangeSearchParam(booleanQuery, param, innerOccurance);
                    if (param.Refinements.ContainsKey("__workflow state"))
                    {
                        SearcherMethods.AddFieldValueClause(booleanQuery, "__workflow state", param.Refinements["__workflow state"], QueryOccurance.Should);
                    }
                    if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug)
                    {
                        Log.Info("Search Clauses Number: " + booleanQuery.Clauses().Count, this);
                    }

                    if (!param.SortByField.IsNullOrEmpty())
                    {
                        return this.RunQuery(booleanQuery, param.PageSize, param.PageNumber, param.SortByField, param.SortDirection);
                    }

                    return param.PageNumber != 0 ? this.RunQuery(booleanQuery, param.PageSize, param.PageNumber) : this.RunQuery(booleanQuery, 20, 0);
                }
            }

            return new KeyValuePair<int, List<SitecoreItem>>();
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumreable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable<SitecoreItem> Search(this Item itm, out int hitCount, string relatedIds = "", string indexName = "itembuckets_buckets", string text = "", string templates = "", string location = "", string sortDirection = "", string language = "en", string id = "", string sortField = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20, int pageNumber = 0)
        {
            var culture = CultureInfo.CreateSpecificCulture("en-US");
            var startDateOut = new DateTime();
            var endDateOut = new DateTime();
            var startFlag = true;
            var endFlag = true;
            if (!DateTime.TryParse(startDate, culture, DateTimeStyles.None, out startDateOut))
            {
                startDateOut = DateTime.Now;
                startFlag = false;
            }

            if (!DateTime.TryParse(endDate, culture, DateTimeStyles.None, out endDateOut))
            {
                endDateOut = DateTime.Now.AddDays(1);
                endFlag = false;
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                                          {
                                              ItemName = itemName,
                                              FullTextQuery = text,
                                              RelatedIds = relatedIds,
                                              TemplateIds = templates,
                                              LocationIds = location.IsEmpty() ? itm.ID.ToString() : location,
                                              Language = language,
                                              ID = id,
                                              SortDirection = sortDirection,
                                              SortByField = sortField,
                                              PageSize = numberOfItemsToReturn,
                                              PageNumber = pageNumber
                                          };
                var keyValuePair = searcher.GetItems(dateSearchParam);

                if (startFlag || endFlag)
                {
                    dateSearchParam.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                                 {
                                                     new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDateOut, endDateOut)
                                                         {
                                                             InclusiveStart = true, InclusiveEnd = true
                                                         }
                                                 };
                }

                hitCount = keyValuePair.Key;
                return keyValuePair.Value;
            }
        }
        public static DateRangeSearchParam GetBaseQuery(List<SearchStringModel> _searchQuery, string locationFilter)
        {
            var startDate = DateTime.Now;
            var endDate = DateTime.Now.AddDays(1);
            var locationSearch = locationFilter;
            var refinements = new SafeDictionary<string>();
            var searchStringModels = GetTags(_searchQuery);

            if (searchStringModels.Count > 0)
            {
                foreach (var ss in searchStringModels)
                {
                    var query = ss.Value;
                    if (query.Contains("tagid="))
                    {
                        query = query.Split('|')[1].Replace("tagid=", string.Empty);
                    }
                    var db = Context.ContentDatabase ?? Context.Database;
                    refinements.Add("_tags", db.GetItem(query).ID.ToString());
                }
            }

            var author = GetAuthor(_searchQuery);
            var languages = GetLanguages(_searchQuery);
            if (languages.Length > 0)
            {
                refinements.Add("_language", languages);
            }

            var references = GetReferences(_searchQuery);

            var custom = GetCustom(_searchQuery);
            if (custom.Length > 0)
            {
                var customSearch = custom.Split('|');
                if (customSearch.Length > 0)
                {
                    try
                    {
                        refinements.Add(customSearch[0], customSearch[1]);
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Could not parse the custom search query", exc);
                    }
                }
            }

            var search = GetField(_searchQuery);
            if (search.Length > 0)
            {
                var customSearch = search;
                refinements.Add(customSearch, GetText(_searchQuery));
            }

            var fileTypes = GetFileTypes(_searchQuery);
            if (fileTypes.Length > 0)
            {
                refinements.Add("extension", GetFileTypes(_searchQuery));
            }

            var s = GetSite(_searchQuery);
            if (s.Length > 0)
            {
                var siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name);
                var db = Context.ContentDatabase ?? Context.Database;
                var startItemId = db.GetItem(siteContext.StartPath);
                locationSearch = startItemId.ID.ToString();
            }

            var culture = CultureInfo.CreateSpecificCulture("en-US");
            var startFlag = true;
            var endFlag = true;
            if (GetStartDate(_searchQuery).Any())
            {
                if (!DateTime.TryParse(GetStartDate(_searchQuery), culture, DateTimeStyles.None, out startDate))
                {
                    startDate = DateTime.Now;
                }

                startFlag = false;
            }

            if (GetEndDate(_searchQuery).Any())
            {
                if (!DateTime.TryParse(GetEndDate(_searchQuery), culture, DateTimeStyles.None, out endDate))
                {
                    endDate = DateTime.Now.AddDays(1);
                }

                endFlag = false;
            }

            var returnResult = new DateRangeSearchParam
            {
                ID = GetID(_searchQuery),
                ShowAllVersions = false,
                FullTextQuery = GetText(_searchQuery),
                Refinements = refinements,
                RelatedIds = references.Any() ? IdHelper.ParseId(references) : null,
                TemplateIds = GetTemplates(_searchQuery),
                LocationIds = IdHelper.ParseId(GetLocation(_searchQuery, locationFilter)),
                Language = languages,
                IsFacet = true,
                Author = author == string.Empty ? string.Empty : author,
            };
            if (!startFlag || !endFlag)
            {
                returnResult.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                             {
                                                 new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate)
                                                 {
                                                     InclusiveStart = true,
                                                     InclusiveEnd = true
                                                 }
                                             };
            }

            return returnResult;
        }
        internal static void ApplyDateRangeSearchParam(BooleanQuery query, DateRangeSearchParam param, BooleanClause.Occur innerOccurance)
        {
            if (param.Ranges == null)
            {
                return;
            }

            if (param.Ranges.Count <= 0)
            {
                return;
            }

            param.Ranges.ForEach(dateParam => AddDateRangeQuery(query, dateParam, innerOccurance));
        }
   /// <summary>
   /// Gets the items from searcher.
   /// </summary>
   /// <param name="searcher">The searcher.</param>
   /// <param name="dateSearchParam">The date search parameter.</param>
   /// <param name="hitCount">The hit count.</param>
   /// <returns>The list of the items.</returns>
   private static IEnumerable<SitecoreItem> GetItemsFromSearcher(
 IndexSearcher searcher, DateRangeSearchParam dateSearchParam, out int hitCount)
   {
       KeyValuePair<int, List<SitecoreItem>> keyValuePair = searcher.GetItems(dateSearchParam);
         hitCount = keyValuePair.Key;
         return keyValuePair.Value;
   }
        /// <summary>
        /// Gets the full parameters.
        /// </summary>
        /// <param name="startLocationItem">The start location item.</param>
        /// <param name="refinements">The refinements.</param>
        /// <param name="relatedIds">The related ids.</param>
        /// <param name="p">The p.</param>
        /// <param name="text">The text.</param>
        /// <param name="templates">The templates.</param>
        /// <param name="location">The location.</param>
        /// <param name="language">The language.</param>
        /// <param name="id">The id.</param>
        /// <param name="sortField">The sort field.</param>
        /// <param name="sortDirection">The sort direction.</param>
        /// <param name="itemName">Name of the item.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="numberOfItemsToReturn">The number of items to return.</param>
        /// <param name="pageNumber">The page number.</param>
        /// <param name="customParametersOccurance">The custom parameters occurrence.</param>
        /// <returns>The date range search parameters.</returns>
        private static DateRangeSearchParam GetFullParameters(
      Item startLocationItem,
      SafeDictionary<string> refinements,
      string relatedIds,
      string p,
      string text,
      string templates,
      string location,
      string language,
      string id,
      string sortField,
      string sortDirection,
      string itemName,
      string startDate,
      string endDate,
      int numberOfItemsToReturn,
      int pageNumber,
      QueryOccurance customParametersOccurance)
        {
            CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

              DateTime startDateOut;
              bool startFlag = true;
              if (!DateTime.TryParse(startDate, culture, DateTimeStyles.None, out startDateOut))
              {
            startDateOut = DateTime.Now;
            startFlag = false;
              }

              DateTime endDateOut;
              bool endFlag = true;
              if (!DateTime.TryParse(endDate, culture, DateTimeStyles.None, out endDateOut))
              {
            endDateOut = DateTime.Now.AddDays(1);
            endFlag = false;
              }

              if (startLocationItem.IsNull())
              {
            Log.Warn("You are trying to run an Search on an item that has a start location of null", null);
            return null;
              }

              var dateSearchParam = new DateRangeSearchParam
              {
            ItemName = itemName,
            FullTextQuery = text,
            RelatedIds = relatedIds,
            TemplateIds = templates,
            LocationIds = startLocationItem.ID.ToString(),
            Language = language,
            ID = id,
            SortDirection = sortDirection,
            SortByField = sortField,
            PageSize = numberOfItemsToReturn,
            PageNumber = pageNumber,
            Refinements = refinements,
            Occurance = customParametersOccurance
              };

              if (startFlag || endFlag)
              {
            dateSearchParam.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                   {
                                     new DateRangeSearchParam.DateRangeField(
                                       SearchFieldIDs.CreatedDate,
                                       startDateOut,
                                       endDateOut)
                                       {
                                         InclusiveStart = true,
                                         InclusiveEnd = true
                                       }
                                   };
              }

              return dateSearchParam;
        }
示例#14
0
        public static DateRangeSearchParam GetSearchSettings(List<SearchStringModel> currentSearchString, string locationFilter)
        {
            var startDate = DateTime.Now;
            var endDate = DateTime.Now.AddDays(1);
            var locationSearch = locationFilter;
            var refinements = new SafeDictionary<string>();
            refinements = GetTagRefinements(currentSearchString);

            var author = SearchHelper.GetAuthor(currentSearchString);

            var languages = SearchHelper.GetLanguages(currentSearchString);
            if (languages.Length > 0)
            {
                refinements.Add("_language", languages);
            }

            var references = SearchHelper.GetReferences(currentSearchString);

            var custom = SearchHelper.GetCustom(currentSearchString);
            if (custom.Length > 0)
            {
                var customSearch = custom.Split('|');
                if (customSearch.Length > 0)
                {
                    try
                    {
                        refinements.Add(customSearch[0], customSearch[1]);
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Could not parse the custom search query", exc);
                    }
                }
            }

            var search = SearchHelper.GetField(currentSearchString);
            if (search.Length > 0)
            {
                var customSearch = search;
                refinements.Add(customSearch, SearchHelper.GetText(currentSearchString));
            }

            var fileTypes = SearchHelper.GetFileTypes(currentSearchString);
            if (fileTypes.Length > 0)
            {
                refinements.Add("extension", SearchHelper.GetFileTypes(currentSearchString));
            }

            var s = SearchHelper.GetSite(currentSearchString);
            if (s.Length > 0)
            {
                SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name);
                var db = Context.ContentDatabase ?? Context.Database;
                var startItemId = db.GetItem(siteContext.StartPath);
                locationSearch = startItemId.ID.ToString();
            }

            var culture = CultureInfo.CreateSpecificCulture("en-US");
            var startFlag = true;
            var endFlag = true;
            if (SearchHelper.GetStartDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetStartDate(currentSearchString), culture, DateTimeStyles.None, out startDate))
                {
                    startDate = DateTime.Now;
                }

                startFlag = false;
            }

            if (SearchHelper.GetEndDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetEndDate(currentSearchString), culture, DateTimeStyles.None, out endDate))
                {
                    endDate = DateTime.Now.AddDays(1);
                }

                endFlag = false;
            }

            var location = SearchHelper.GetLocation(currentSearchString, locationSearch);

            var rangeSearch = new DateRangeSearchParam
            {
                ID = SearchHelper.GetID(currentSearchString).IsEmpty() ? SearchHelper.GetRecent(currentSearchString) : SearchHelper.GetID(currentSearchString),
                ShowAllVersions = false,
                FullTextQuery = SearchHelper.GetText(currentSearchString),
                Refinements = refinements,
                RelatedIds = references.Any() ? references : string.Empty,
                TemplateIds = SearchHelper.GetTemplates(currentSearchString),
                LocationIds = location,
                Language = languages,
                Author = author == string.Empty ? string.Empty : author,
                ItemName = SearchHelper.GetItemName(currentSearchString)
            };

            if (!startFlag || !endFlag)
            {
                rangeSearch.Ranges = new List<DateRangeSearchParam.DateRangeField>
                                             {
                                                 new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate)
                                                     {
                                                         InclusiveStart = true, InclusiveEnd = true
                                                     }
                                             };
            }
            return rangeSearch;
        }