//public virtual List<SitecoreItem> GetRelatedItemsByField(FieldSearchParam param) //{ // //string relatedIds, string templateIds, string fieldName, bool partial // var globalQuery = new CombinedQuery(); // ApplyTemplateFilter(globalQuery, param.TemplateIds); // var translator = new QueryTranslator(Index); // var booleanQuery = translator.ConvertCombinedQuery(globalQuery); // AddPartialFieldValueClause(booleanQuery, param.FieldName, param.RelatedIds); // return RunQuery(booleanQuery, param.ShowAllVersions); //} public virtual bool ContainsItemsByFields(string ids, string fieldName, string fieldValue) { var globalQuery = new CombinedQuery(); ApplyIdFilter(globalQuery, BuiltinFields.ID, ids); AddFieldValueClause(globalQuery, fieldName, fieldValue, QueryOccurance.Must); return RunQuery(globalQuery).Count > 0; }
internal static void AddFieldValueClause(CombinedQuery query, string fieldName, string fieldValue, QueryOccurance occurance) { if (fieldName.IsNullOrEmpty() || fieldValue.IsNullOrEmpty()) { return; } fieldValue = IdHelper.ProcessGUIDs(fieldValue); query.Add(new FieldQuery(fieldName, fieldValue), occurance); }
public virtual BooleanQuery ConvertCombinedQuery(CombinedQuery query) { var booleanQuery = new BooleanQuery(); foreach (var clause in query.Clauses) { this.TranslateCombinedQuery(clause, booleanQuery); } return booleanQuery; }
private QueryBase CreateQuery(Database database) { var query = new CombinedQuery(); var databaseQuery = new FieldQuery(BuiltinFields.Database, database.Name); var languageQuery = new FieldQuery(BuiltinFields.Language, Context.Language.Name); var templateQuery = new FieldQuery(BuiltinFields.Template, ShortID.Encode(RewriteReportItem.TemplateId)); query.Add(databaseQuery, QueryOccurance.Must); query.Add(languageQuery, QueryOccurance.Must); query.Add(templateQuery, QueryOccurance.Must); return query; }
public virtual BooleanQuery ConvertCombinedQuery(CombinedQuery query) { var booleanQuery = new BooleanQuery(); foreach (var clause in query.Clauses) { var translatedQuery = Translate(clause.Query); if (translatedQuery != null) { booleanQuery.Add(translatedQuery, GetOccur(clause.Occurance)); } } return booleanQuery; }
protected CombinedQuery ApplyRefinements(IEnumerable<Refinement> refinements, QueryOccurance occurance) { if (refinements.Count() <= 0) return new CombinedQuery(); var innerQuery = new CombinedQuery(); foreach (var refinement in refinements) { AddFieldValueClause(innerQuery, refinement.Name, refinement.Value, occurance); } return innerQuery; }
public virtual List <SkinnyItem> GetItemsInRange(DateRangeSearchParam param) { var globalQuery = new CombinedQuery(); ApplyLanguageClause(globalQuery, param.Language); ApplyTemplateFilter(globalQuery, param.TemplateIds); ApplyLocationFilter(globalQuery, param.LocationIds); ApplyFullTextClause(globalQuery, param.FullTextQuery); var translator = new QueryTranslator(Index); var booleanQuery = translator.ConvertCombinedQuery(globalQuery); var innerOccurance = translator.GetOccur(param.Occurance); ApplyDateRangeSearchParam(booleanQuery, param, innerOccurance); return(RunQuery(booleanQuery, param.ShowAllVersions)); }
protected void ApplyRefinements(CombinedQuery query, SafeDictionary <string> refinements, QueryOccurance occurance) { if (refinements.Count <= 0) { return; } var innerQuery = new CombinedQuery(); foreach (var refinement in refinements) { var fieldName = refinement.Key.ToLowerInvariant(); var fieldValue = refinement.Value; AddFieldValueClause(innerQuery, fieldName, fieldValue, occurance); } query.Add(innerQuery, QueryOccurance.Must); }
public CombinedQuery CreateSingleAssayCombinedQuery(CombinedQuery cQuery, AssayPanelQuery apQuery) { var singleAssayCombinedQuery = new CombinedQuery { ProjectId = cQuery.ProjectId, ClinicalObservations = cQuery.ClinicalObservations, DesignElements = cQuery.DesignElements, GroupedObservations = cQuery.GroupedObservations, SubjectCharacteristics = cQuery.SubjectCharacteristics, UserId = cQuery.UserId, Id = Guid.NewGuid() }; singleAssayCombinedQuery.AssayPanels.Add(apQuery); _combinedQueryRepository.Insert(singleAssayCombinedQuery); return(singleAssayCombinedQuery); }
protected void ApplyIdFilter(CombinedQuery query, string fieldName, string filter, QueryOccurance occurance) { if (String.IsNullOrEmpty(fieldName) || String.IsNullOrEmpty(filter)) { return; } var filterQuery = new CombinedQuery(); var values = IdHelper.ParseId(filter); foreach (var value in values.Where(ID.IsID)) { AddFieldValueClause(filterQuery, fieldName, value, QueryOccurance.Should); } query.Add(filterQuery, occurance); }
public virtual BooleanQuery ProcessQuery(QueryOccurance occurance, Index index) { var innerQuery = new CombinedQuery(); ApplyFullTextClause(innerQuery, FullTextQuery, occurance); ApplyRelationFilter(innerQuery, RelatedIds, occurance); ApplyTemplateFilter(innerQuery, TemplateIds, occurance); ApplyLocationFilter(innerQuery, LocationIds, occurance); AddFieldValueClause(innerQuery, BuiltinFields.Database, Database, occurance); if (innerQuery.Clauses.Count < 1) return null; var translator = new QueryTranslator(index); var booleanQuery = translator.ConvertCombinedQuery(innerQuery); ApplyLanguageClause(booleanQuery, Language, translator.GetOccur(occurance)); return booleanQuery; }
internal static void ApplyFullTextClause(CombinedQuery query, string searchText, string indexName) { if (searchText.IsNullOrEmpty()) { return; } var combinedQuery = new CombinedQuery(); combinedQuery.Add(new FullTextQuery(searchText), QueryOccurance.Should); combinedQuery.Add(new FieldQuery(BuiltinFields.Name, searchText), QueryOccurance.Should); if (!indexName.IsNullOrEmpty()) { AppendIndexSpecificTerms(combinedQuery, indexName, searchText); } query.Add(combinedQuery, QueryOccurance.Must); }
public static IEnumerable <Item> GetRelatedDocuments([NotNull] IEnumerable <RelationInfo> categories) { Assert.ArgumentNotNull(categories, "categories"); var index = SearchManager.SystemIndex; if (index == null) { return(new Item[0]); } var query = new CombinedQuery(categories.Select(info => new QueryClause(new FieldQuery("_categories", ShortID.Encode(info.Category)), QueryOccurance.Should))); SearchResultCollection collection; using (var context = index.CreateSearchContext()) { collection = context.Search(query).FetchResults(0, 10); } return(collection.Select(result => SearchManager.GetObject(result) as Item).Where(item => item != null)); }
public SitecoreSearchResultCollection FieldSearch(QueryInfo[] qis, int maxResults) { HighResTimer timer = new HighResTimer(true); var combinedQuery = new CombinedQuery(); foreach (var qi in qis) { var q = GetQuery(qi); if (q != null) combinedQuery.Add(q, qi.SitecoreSearchQueryOccurance); } SearchResultCollection results = null; if (combinedQuery.Clauses.Count > 0) results = GetSearchHits(combinedQuery, maxResults); return results != null ? new SitecoreSearchResultCollection(results, timer.Elapsed()) : null; }
public virtual BooleanQuery ProcessQuery(QueryOccurance occurance, Index index) { var innerQuery = new CombinedQuery(); ApplyFullTextClause(innerQuery, FullTextQuery, occurance); ApplyRelationFilter(innerQuery, RelatedIds, occurance); ApplyTemplateFilter(innerQuery, TemplateIds, occurance); ApplyLocationFilter(innerQuery, LocationIds, occurance); AddFieldValueClause(innerQuery, BuiltinFields.Database, Database, occurance); if (innerQuery.Clauses.Count < 1) { return(null); } var translator = new QueryTranslator(index); var booleanQuery = translator.ConvertCombinedQuery(innerQuery); ApplyLanguageClause(booleanQuery, Language, translator.GetOccur(occurance)); return(booleanQuery); }
public static CombinedQueryDTO GetcQueryDTO(CombinedQuery cQuery) { var dto = new CombinedQueryDTO(); dto.Id = cQuery.Id.ToString(); dto.Name = cQuery.Name; dto.UserId = cQuery.UserId.ToString(); dto.ObsRequests = new List <ObservationRequestDTO>(); foreach (var oq in cQuery.ClinicalObservations.Union(cQuery.GroupedObservations)) { dto.ObsRequests.Add(GetDTOforQuery(oq)); } foreach (var oq in cQuery.SubjectCharacteristics.Union(cQuery.DesignElements)) { dto.SubjCharRequests.Add(GetDTOforQuery(oq)); } foreach (var apq in cQuery.AssayPanels) { dto.AssayPanelRequests.Add(apq.AssayId, GetDTOforAssayPanelQuery(apq)); } return(dto); }
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>>(); }
private UserDataset CreateOrFindSubjectClinicalDataset(CombinedQuery query, string userId) { var phenoDataset = _userDatasetRepository.FindSingle( d => d.ProjectId == query.ProjectId && d.QueryId == query.Id && d.Type == "PHENO" && d.OwnerId == userId); if (phenoDataset != null) { return(phenoDataset); } phenoDataset = new UserDataset { Id = Guid.NewGuid(), OwnerId = userId, ProjectId = query.ProjectId, Type = "PHENO", Name = "Subjects", QueryId = query.Id, FileStatus = 0, }; //ADD SUBJECTID & STUDYID DATAFIELD phenoDataset.Fields.Add(CreateSubjectIdField()); phenoDataset.Fields.Add(CreateStudyIdField()); //ADD DESIGN ELEMENT FIELDS (STUDY, VISIT, ARM...etc) phenoDataset.Fields.AddRange(query.DesignElements.Select(qObj => new DatasetField() { QueryObject = qObj, QueryObjectType = qObj.QueryFor, ColumnHeader = qObj.QueryObjectName })); //ADD SUBJECT CHARACTERISTICS (AGE, RACE, SEX ...etc) phenoDataset.Fields.AddRange(query.SubjectCharacteristics.Select(qObj => new DatasetField() { QueryObject = qObj, QueryObjectType = nameof(SubjectCharacteristic), ColumnHeader = qObj.QueryObjectName//.ObservationName })); //ADD CLINICAL OBSERVATIONS foreach (var co in query.ClinicalObservations) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = co, QueryObjectType = nameof(SdtmRow), ColumnHeader = co.ObservationName }); if (co.HasLongitudinalData) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = new Query() { QueryFor = nameof(Visit), QueryFrom = nameof(SdtmRow), QuerySelectProperty = "Name" }, QueryObjectType = nameof(Visit), ColumnHeader = "visit" }); } if (co.HasTPT) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = new Query() { QueryFor = nameof(SdtmRow.CollectionStudyTimePoint), QueryFrom = nameof(SdtmRow), QuerySelectProperty = "Name" }, QueryObjectType = nameof(RelativeTimePoint), ColumnHeader = "timepoint" }); } } //phenoDataset.Fields.AddRange(query.ClinicalObservations.Select(qObj => new DatasetField() //{ // QueryObject = qObj, // QueryObjectType = nameof(SdtmRow), // ColumnHeader = qObj.ObservationName //})); //ADD GROUPED CLINICAL OBSERVATIONS phenoDataset.Fields.AddRange(query.GroupedObservations.Select(gObs => new DatasetField() { QueryObject = gObs, QueryObjectType = nameof(SdtmRow), ColumnHeader = gObs.ObservationName })); var exportData = _queryService.GetQueryResult(query.Id); phenoDataset.SubjectCount = exportData.Subjects.Count; _userDatasetRepository.Insert(phenoDataset); _dataContext.Save(); return(phenoDataset); }
protected void ApplyRelationFilter(CombinedQuery query, string ids, QueryOccurance occurance) { ApplyIdFilter(query, BuiltinFields.Links, ids, occurance); }
public CombinedQuery SaveQuery(CombinedQueryDTO cdto, string userId, int projectId) { CombinedQuery cQuery = new CombinedQuery(); cQuery.Name = cdto.Name; cQuery.UserId = Guid.Parse(userId); cQuery.ProjectId = projectId; cQuery.Id = Guid.NewGuid(); cQuery.IsSavedByUser = cdto.IsSavedByUser; var requests = cdto.ObsRequests.Union(cdto.SubjCharRequests); foreach (var request in requests) { if (!request.IsMultipleObservations) { var query = GetQueryFromQueryDTO(request); if (request.IsSubjectCharacteristics) { cQuery.SubjectCharacteristics.Add(query); } if (request.IsClinicalObservations) { cQuery.ClinicalObservations.Add((ObservationQuery)query); } if (request.IsDesignElement) { cQuery.DesignElements.Add(query); } } else { var goq = new GroupedObservationsQuery() { //Name = request.Name, GroupedObsName = request.O3, PropertyName = request.QO2, PropertyLabel = request.QO2_label, PropertyId = request.QO2id, Group = request.Group, GroupedObservations = new List <ObservationQuery>(), DataType = request.DataType, FilterExactValues = request.FilterExactValues, FilterRangeFrom = request.FilterRangeFrom, FilterRangeTo = request.FilterRangeTo, IsFiltered = request.IsFiltered, ProjectId = request.ProjectId }; goq.GroupedObservations.AddRange(request.GroupedObservations.Select(obsReq => new ObservationQuery() { TermId = obsReq.O3id, TermName = obsReq.O3, PropertyId = obsReq.QO2id, PropertyName = obsReq.QO2, Group = obsReq.Group, IsOntologyEntry = obsReq.IsOntologyEntry, TermCategory = obsReq.OntologyEntryCategoryName, DataType = obsReq.DataType, ProjectId = obsReq.ProjectId })); cQuery.GroupedObservations.Add(goq); } } var assaypanels = cdto.AssayPanelRequests.Values.Where(ap => ap.IsRequested); foreach (var assayRequest in assaypanels) { var assayPanelQuery = new AssayPanelQuery(); assayPanelQuery.AssayId = assayRequest.AssayId; assayPanelQuery.AssayName = assayRequest.AssayName; foreach (var sampleQuery in assayRequest.SampleQuery) { var query = GetQueryFromQueryDTO(sampleQuery); assayPanelQuery.SampleQueries.Add(query); } cQuery.AssayPanels.Add(assayPanelQuery); } return(_combinedQueryRepository.Insert(cQuery)); }
protected void ApplyRelationFilter(CombinedQuery query, string ids) { ApplyIdFilter(query, BuiltinFields.Links, ids); }
private ExportFileDefinition GetSubjectFileDefinition(CombinedQuery query) { var phenoDataset = new ExportFileDefinition() { ProjectId = query.ProjectId, ContentType = "PHENO", Name = "Subjects", QueryId = query.Id }; bool _hasLongitudinalData = false, _hasTpt = false; //ADD SUBJECTID & STUDYID DATAFIELD phenoDataset.Fields.Add(CreateSubjectIdField()); phenoDataset.Fields.Add(CreateStudyIdField()); //ADD DESIGN ELEMENT FIELDS (STUDY, VISIT, ARM...etc) phenoDataset.Fields.AddRange(query.DesignElements.Select(qObj => new DatasetField() { QueryObject = qObj, QueryObjectType = qObj.QueryFor, ColumnHeader = qObj.QueryObjectName })); //ADD SUBJECT CHARACTERISTICS (AGE, RACE, SEX ...etc) phenoDataset.Fields.AddRange(query.SubjectCharacteristics.Select(qObj => new DatasetField() { QueryObject = qObj, QueryObjectType = nameof(SubjectCharacteristic), ColumnHeader = qObj.QueryObjectName//.ObservationName })); //ADD CLINICAL OBSERVATIONS foreach (var co in query.ClinicalObservations) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = co, QueryObjectType = nameof(SdtmRow), ColumnHeader = co.ObservationName }); if (co.HasLongitudinalData) { _hasLongitudinalData = true; } if (co.HasTPT) { _hasTpt = true; } } //ADD GROUPED CLINICAL OBSERVATIONS phenoDataset.Fields.AddRange(query.GroupedObservations.Select(gObs => new DatasetField() { QueryObject = gObs, QueryObjectType = nameof(SdtmRow), ColumnHeader = gObs.ObservationName })); //ADD longitudinal data columns if (_hasLongitudinalData && !phenoDataset.Fields.Exists(f => f.ColumnHeader == "visit")) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = new Query() { QueryFor = nameof(Visit), QueryFrom = nameof(SdtmRow), QuerySelectProperty = "Name" }, QueryObjectType = nameof(Visit), ColumnHeader = "visit" }); } if (_hasTpt && !phenoDataset.Fields.Exists(f => f.ColumnHeader == "timepoint")) { phenoDataset.Fields.Add(new DatasetField() { QueryObject = new Query() { QueryFor = nameof(SdtmRow.CollectionStudyTimePoint), QueryFrom = nameof(SdtmRow), QuerySelectProperty = "Name" }, QueryObjectType = nameof(RelativeTimePoint), ColumnHeader = "timepoint" }); } return(phenoDataset); }
protected void ApplyRefinements(CombinedQuery query, SafeDictionary<string> refinements, QueryOccurance occurance) { if (refinements.Count <= 0) return; var innerQuery = new CombinedQuery(); foreach (var refinement in refinements) { var fieldName = refinement.Key.ToLowerInvariant(); var fieldValue = refinement.Value; AddFieldValueClause(innerQuery, fieldName, fieldValue, occurance); } query.Add(innerQuery, QueryOccurance.Must); }
internal static void ApplyFullTextClause(CombinedQuery query, string searchText) { ApplyFullTextClause(query, searchText, string.Empty); }
protected void ApplyRelationFilter(CombinedQuery query, string ids, QueryOccurance occurance) { ApplyIdFilter(query, BuiltinFields.Links, ids, occurance); }
protected void ApplyLocationFilter(CombinedQuery query, string locationIds, QueryOccurance occurance) { ApplyIdFilter(query, BuiltinFields.Path, locationIds, occurance); }
private void _getObservations(CombinedQuery combinedQuery, ref DataExportObject queryResult) { List <SdtmRow> observations = new List <SdtmRow>(); HashSet <string> ObsFilteredSubjectIds = new HashSet <string>(); //GROUP CLINICAL OBSERVATIONS (GROUP AND INDIVIDUAL) var obsQueries = combinedQuery.ClinicalObservations.Union(combinedQuery.GroupedObservations).ToList(); //GROUP CLINICAL OBSERVATIONS BY O3 TO QUERY FOR THE OBSERVATION (E.G. HEADACHE ONLY ONCE EVEN IF TWO REQUEST ARE MADE (e.g. AEOCCUR and AESEV) var queriesByO3Id = obsQueries.GroupBy(f => f.QueryObjectName).ToList(); foreach (var sameO3queries in queriesByO3Id) { var o3q_g = sameO3queries.Select(group => group).First(); var o3q_list = new List <ObservationQuery>(); //EXPANIDNG ALL to GROUP TO ACCOMMODATE FOR GROUP OBSERVATIONS AS WELL IN THE SAME CODE BLOCK if (o3q_g.GetType().Name == nameof(GroupedObservationsQuery)) { ((GroupedObservationsQuery)o3q_g).GroupedObservations.ForEach(oq => o3q_list.Add(oq)); } else { o3q_list.Add(o3q_g); } ////////////////////////////////////////////////////////////////////////////////////////////// var obsQueryResult = new List <SdtmRow>(); //QUERYING FOR OBSERVATIONS foreach (var o3q in o3q_list) { var _observations = o3q.IsOntologyEntry ? _sdtmRepository.FindAll(s => s.QualifierQualifiers[o3q.TermCategory] == o3q.TermId.ToString() && s.Group == o3q.Group && s.ProjectId == o3q.ProjectId).ToList() : _sdtmRepository.FindAll(s => s.DBTopicId == o3q.TermId && s.ProjectId == o3q.ProjectId).ToList(); obsQueryResult.AddRange(_observations); if (_observations.Count > queryResult.Subjects.Count) { queryResult.HasLongitudinalData = true; } } //FILTERING OBSERVATIONS foreach (var oq in sameO3queries) //AEOCCUR / AESEV { if (!oq.IsFiltered) { continue; } //HACK FOR FINDINGS SHOULD GO AWAY IN THE NEW OBSERVATION MODEL obsQueryResult.ForEach(o => o.Qualifiers = o.ResultQualifiers.Union(o.Qualifiers).ToDictionary(p => p.Key, p => p.Value)); string v = null; float vn; obsQueryResult = oq.DataType == "string" ? obsQueryResult.FindAll( s => s.Qualifiers.TryGetValue(oq.PropertyName, out v) && oq.FilterExactValues.Contains(s.Qualifiers[oq.PropertyName])) : obsQueryResult.FindAll( s => float.TryParse(s.Qualifiers[oq.PropertyName], out vn) && vn >= oq.FilterRangeFrom && vn <= oq.FilterRangeTo); var filteredSubjectIds = obsQueryResult.Select(o => o.USubjId).Distinct().ToList(); if (!ObsFilteredSubjectIds.Any()) { ObsFilteredSubjectIds.UnionWith(filteredSubjectIds); } ObsFilteredSubjectIds.IntersectWith(filteredSubjectIds); queryResult.ObservationsFiltered = true; } observations.AddRange(obsQueryResult); } //CASCADE FILTERING OF OBERVATIONS FROM ALL FILTERS ON OBSERVATIONS if (queryResult.ObservationsFiltered) { observations = observations.FindAll(o => ObsFilteredSubjectIds.Contains(o.USubjId)); } queryResult.Observations = observations; }
private QueryBase GetQuery() { QueryBase base2 = null; NameValueCollection fieldValues = GetFieldValues(); string str = StringUtil.GetString(new string[] { Context.ClientPage.ClientRequest.Form["TreeSearch"] }); if (str == "Search") { str = string.Empty; } str = str.Trim(); if (!string.IsNullOrEmpty(str)) { base2 = new FullTextQuery(str); } if (fieldValues.Count <= 0) { return base2; } CombinedQuery query = new CombinedQuery(); foreach (string str2 in fieldValues.AllKeys) { string fieldValue = fieldValues[str2]; if (fieldValue.Length > 0) { query.Add(new FieldQuery(str2.ToLowerInvariant(), fieldValue), QueryOccurance.Should); } } return query; }
public virtual List<SkinnyItem> GetItems(FieldValueSearchParam param) { var globalQuery = new CombinedQuery(); ApplyLanguageClause(globalQuery, param.Language); ApplyFullTextClause(globalQuery, param.FullTextQuery); ApplyRelationFilter(globalQuery, param.RelatedIds); ApplyTemplateFilter(globalQuery, param.TemplateIds); ApplyLocationFilter(globalQuery, param.LocationIds); ApplyRefinements(globalQuery, param.Refinements, param.Occurance); return RunQuery(globalQuery, param.ShowAllVersions); }
/// <summary> /// Gets the comments for the given blog entry /// </summary> /// <param name="item">The item to get the comments under</param> /// <param name="maximumCount">The maximum number of comments to retrieve</param> /// <param name="language">The language to get the comments in</param> /// <returns>The comments which are decendants of the given item</returns> public CommentItem[] GetCommentsFor(Item item, int maximumCount, bool sort = false, bool reverse = false) { if (item != null && maximumCount > 0) { var blog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(item); if (blog != null) { #if FEATURE_CONTENT_SEARCH var indexName = Settings.SearchIndexName; List <CommentItem> result = new List <CommentItem>(); if (!string.IsNullOrEmpty(indexName)) { using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext()) { var indexresults = context.GetQueryable <CommentResultItem>().Where(x => x.Paths.Contains(item.ID) && x.TemplateId == blog.BlogSettings.CommentTemplateID && x.DatabaseName.Equals(Context.Database.Name, StringComparison.InvariantCulture) && x.Language == item.Language.Name ); if (indexresults.Any()) { if (sort) { indexresults = indexresults.OrderByDescending(x => x.CreatedDate); } else if (reverse) { indexresults = indexresults.OrderBy(x => x.CreatedDate); } indexresults = indexresults.Take(maximumCount); // Had some odd issues with the linq layer. Array to avoid them. var indexresultsList = indexresults.ToArray(); var items = from resultItem in indexresultsList let i = resultItem.GetItem() where i != null select i; result = items.Select(x => new CommentItem(x)).ToList(); } } } return(result.ToArray()); #else var query = new CombinedQuery(); // TODO: What about items using templates derived from commenttemplateid? need to accommodate those query.Add(new FieldQuery(Constants.Index.Fields.Template, blog.BlogSettings.CommentTemplateID.ToShortID().ToString().ToLower()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Path, item.ID.ToShortID().ToString()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Language, item.Language.Name), QueryOccurance.Must); string sortField = null; if (sort) { sortField = Constants.Index.Fields.Created; } var searcher = new Searcher(); return(searcher.Execute <CommentItem>(query, item.Language, maximumCount, (list, listItem) => list.Add((CommentItem)listItem), sortField, reverse)); #endif } } return(new CommentItem[0]); }
protected void ApplyLocationFilter(CombinedQuery query, string locationIds) { ApplyIdFilter(query, BuiltinFields.Path, locationIds); }
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); }
protected void ApplyRelationFilter(CombinedQuery query, string ids) { ApplyIdFilter(query, BuiltinFields.Links, ids); }
public static IEnumerable<Item> GetRelatedDocuments([NotNull] IEnumerable<RelationInfo> categories) { Assert.ArgumentNotNull(categories, "categories"); var index = SearchManager.SystemIndex; if (index == null) { return new Item[0]; } var query = new CombinedQuery(categories.Select(info => new QueryClause(new FieldQuery("_categories", ShortID.Encode(info.Category)), QueryOccurance.Should))); SearchResultCollection collection; using (var context = index.CreateSearchContext()) { collection = context.Search(query).FetchResults(0, 10); } return collection.Select(result => SearchManager.GetObject(result) as Item).Where(item => item != null); }
//public virtual List<SitecoreItem> GetItemsViaTermQuery(string fieldName, string fieldValue) //{ // var query = new TermQuery(new Term(fieldName, fieldValue)); // return RunQuery(query, false); //} //public virtual List<SitecoreItem> GetItemsViaFieldQuery(string fieldName, string fieldValue) //{ // var query = new FieldQuery(fieldName, fieldValue); // return RunQuery(query, false); //} public virtual List<SitecoreItem> GetItems(SearchParam param) { var globalQuery = new CombinedQuery(); ApplyLanguageClause(globalQuery, param.Language); if (!String.IsNullOrWhiteSpace(param.FullTextQuery)) { ApplyFullTextClause(globalQuery, param.FullTextQuery); } ApplyRelationFilter(globalQuery, param.RelatedIds); ApplyTemplateFilter(globalQuery, param.TemplateIds); ApplyLocationFilter(globalQuery, param.LocationIds); return RunQuery(globalQuery, param.ShowAllVersions); }
protected void AddFieldValueClause(CombinedQuery query, string fieldName, string fieldValue, QueryOccurance occurance) { if (String.IsNullOrEmpty(fieldName) || String.IsNullOrEmpty(fieldValue)) return; // if we are searching by _id field, do not lowercase fieldValue = IdHelper.ProcessGUIDs(fieldValue); query.Add(new FieldQuery(fieldName.ToLowerInvariant(), fieldValue), occurance); }
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); } 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> >()); }
protected void ApplyIdFilter(CombinedQuery query, string fieldName, string filter, QueryOccurance occurance) { if (String.IsNullOrEmpty(fieldName) || String.IsNullOrEmpty(filter)) return; var filterQuery = new CombinedQuery(); var values = IdHelper.ParseId(filter); foreach (var value in values.Where(ID.IsID)) { AddFieldValueClause(filterQuery, fieldName, value, QueryOccurance.Should); } query.Add(filterQuery, occurance); }
public static IEnumerable<Item> GetItemsInCategories([NotNull] IEnumerable<ID> categories) { Assert.ArgumentNotNull(categories, "categories"); var index = SearchManager.SystemIndex; if (index == null) { return new Item[0]; } var query = new CombinedQuery(); foreach (var id in categories) { query.Add(new FieldQuery("_categories", ShortID.Encode(id)), QueryOccurance.Must); } SearchResultCollection collection; using (var context = index.CreateSearchContext()) { collection = context.Search(query).FetchResults(0, int.MaxValue); } return collection.Select(result => SearchManager.GetObject(result)).OfType<Item>(); }
internal static void ApplyTemplateNotFilter(CombinedQuery query) { query.Add(new FieldQuery(BuiltinFields.Template, IdHelper.NormalizeGuid(Config.ContainerTemplateId)), QueryOccurance.MustNot); }
internal static void ApplyCombinedLocationFilter(CombinedQuery query, string locationIds) { ApplyIdFilter(query, BuiltinFields.Path, locationIds); }
internal static void ApplyRelationFilter(CombinedQuery query, string ids) { ApplyIdFilter(query, BuiltinFields.Links, ids); }
protected void ApplyFullTextClause(CombinedQuery query, string searchText, QueryOccurance occurance) { if (String.IsNullOrEmpty(searchText)) return; query.Add(new FullTextQuery(searchText), occurance); }
internal static void ApplyLatestVersion(CombinedQuery globalQuery) { var fieldQuery = new FieldQuery(BuiltinFields.LatestVersion, "1"); globalQuery.Add(fieldQuery, QueryOccurance.Must); }
protected void ApplyLocationFilter(CombinedQuery query, string locationIds, QueryOccurance occurance) { ApplyIdFilter(query, BuiltinFields.Path, locationIds, occurance); }
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; }
protected void ApplyTemplateFilter(CombinedQuery query, string templateIds, QueryOccurance occurance) { if (String.IsNullOrEmpty(templateIds)) return; templateIds = IdHelper.NormalizeGuid(templateIds); var fieldQuery = new FieldQuery(BuiltinFields.Template, templateIds); query.Add(fieldQuery, occurance); }
/// <summary> /// Gets blog entries for the given blog up to the maximum number given /// </summary> /// <param name="blog">The blog item to get the entries for</param> /// <param name="maxNumber">The maximum number of entries to retrieve</param> /// <param name="tag">A tag the entry must contain</param> /// <param name="category">A category the entry must contain</param> /// <param name="minimumDate">The minimum date for entries</param> /// <param name="maximumDate">The maximum date for the entries</param> /// <returns></returns> public EntryItem[] GetBlogEntries(Item blog, int maxNumber, string tag, string category, DateTime?minimumDate = null, DateTime?maximumDate = null) { if (blog == null || maxNumber <= 0) { return(new EntryItem[0]); } BlogHomeItem customBlogItem = null; if (blog.TemplateIsOrBasedOn(Settings.BlogTemplateID)) { customBlogItem = blog; } else { customBlogItem = blog.GetCurrentItem(Settings.BlogTemplateIDString); } if (customBlogItem == null) { return(new EntryItem[0]); } List <EntryItem> result = new List <EntryItem>(); #if FEATURE_CONTENT_SEARCH var indexName = Settings.SearchIndexName; if (!string.IsNullOrEmpty(indexName)) { using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck)) { var builder = PredicateBuilder.True <EntryResultItem>(); var id = customBlogItem.BlogSettings.EntryTemplateID; builder = builder.And(i => i.TemplateId == id); builder = builder.And(i => i.Paths.Contains(customBlogItem.ID)); builder = builder.And(i => i.Language.Equals(customBlogItem.InnerItem.Language.Name, StringComparison.InvariantCulture)); builder = builder.And(item => item.DatabaseName.Equals(Context.Database.Name, StringComparison.InvariantCulture)); // Tag if (!string.IsNullOrEmpty(tag)) { builder = builder.And(i => i.Tags.Contains(tag)); } // Categories if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(customBlogItem, category); // If the category is unknown, don't return any results. if (categoryItem == null) { return(new EntryItem[0]); } #if SC70 var normalizedID = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(categoryItem.ID); builder = builder.And(i => i.Category.Contains(normalizedID)); #else builder = builder.And(i => i.Category.Contains(categoryItem.ID)); #endif } if (minimumDate != null) { builder = builder.And(i => i.CreatedDate >= minimumDate); } if (maximumDate != null) { builder = builder.And(i => i.CreatedDate < maximumDate); } var indexresults = context.GetQueryable <EntryResultItem>().Where(builder); if (indexresults.Any()) { result = indexresults.Select(i => new EntryItem(i.GetItem())).ToList(); result = result.OrderByDescending(post => post.EntryDate.DateTime).Take(maxNumber).ToList(); } } } #else var query = new CombinedQuery(); //query.Add(new FieldQuery(Constants.Index.Fields.BlogID, blog.ID.ToShortID().ToString().ToLower()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Path, customBlogItem.ID.ToShortID().ToString()), QueryOccurance.Must); query.Add(new FieldQuery(Constants.Index.Fields.Template, customBlogItem.BlogSettings.EntryTemplateID.ToShortID().ToString().ToLower()), QueryOccurance.Must); if (!string.IsNullOrEmpty(tag)) { query.Add(new FieldQuery(Constants.Index.Fields.Tags, DatabaseCrawler.TransformCSV(tag)), QueryOccurance.Must); } if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(blog, category); ID id = ID.Null; // If the category is unknown, don't return any results. if (categoryItem == null) { return(new EntryItem[0]); } id = categoryItem.ID; query.Add(new FieldQuery(Constants.Index.Fields.Category, id.ToShortID().ToString().ToLower()), QueryOccurance.Must); } if (minimumDate != null) { query.Add(new FieldQuery(Constants.Index.Fields.Created, minimumDate.Value.Year.ToString() + minimumDate.Value.Month.ToString() + "*"), QueryOccurance.Must); } var searcher = new Searcher(); result = searcher.Execute <EntryItem>(query, blog.Language, maxNumber, (list, item) => list.Add((EntryItem)item), Constants.Index.Fields.EntryDate, false).ToList(); #endif return(result.ToArray()); }
internal virtual bool ContainsItemsByFields(string ids, string fieldName, string fieldValue) { var globalQuery = new CombinedQuery(); SearcherMethods.ApplyIdFilter(globalQuery, BuiltinFields.ID, ids); SearcherMethods.AddFieldValueClause(globalQuery, fieldName, fieldValue, QueryOccurance.Must); return this.RunQuery(globalQuery).Value.Any(); }
protected void ApplyLocationFilter(CombinedQuery query, string locationIds) { ApplyIdFilter(query, BuiltinFields.Path, locationIds); }
internal virtual KeyValuePair<int, List<SitecoreItem>> GetItems(FieldValueSearchParam param) { var globalQuery = new CombinedQuery(); SearcherMethods.ApplyLanguageClause(globalQuery, param.Language); if (!string.IsNullOrWhiteSpace(param.FullTextQuery)) { SearcherMethods.ApplyFullTextClause(globalQuery, param.FullTextQuery); } SearcherMethods.ApplyRelationFilter(globalQuery, param.RelatedIds); SearcherMethods.ApplyTemplateFilter(globalQuery, param.TemplateIds); SearcherMethods.ApplyLocationFilter(globalQuery, param.LocationIds); SearcherMethods.ApplyRefinements(globalQuery, param.Refinements, param.Occurance); return this.RunQuery(globalQuery); }
/// <summary> /// Gets blog entries for the given blog up to the maximum number given /// </summary> /// <param name="blog">The blog item to get the entries for</param> /// <param name="maxNumber">The maximum number of entries to retrieve</param> /// <param name="tag">A tag the entry must contain</param> /// <param name="category">A category the entry must contain</param> /// <returns></returns> public EntryItem[] GetBlogEntries(Item blog, int maxNumber, string tag, string category, string datePrefix = null) { if (blog == null || maxNumber <= 0) { return(new EntryItem[0]); } BlogHomeItem customBlogItem = null; if (blog.TemplateIsOrBasedOn(Settings.BlogTemplateID)) { customBlogItem = blog; } else { customBlogItem = blog.GetCurrentItem(Settings.BlogTemplateIDString); } if (customBlogItem == null) { return(new EntryItem[0]); } List <EntryItem> result = new List <EntryItem>(); #if FEATURE_CONTENT_SEARCH var indexName = Settings.SearchIndexName; if (!string.IsNullOrEmpty(indexName)) { using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext()) { var builder = PredicateBuilder.True <EntryResultItem>(); var id = Settings.EntryTemplateID; builder = builder.And(i => i.TemplateId == id); // Tag if (!String.IsNullOrEmpty(tag)) { builder = builder.And(PredicateController.BlogTags(tag)); } // Categories if (!string.IsNullOrEmpty(category)) { builder = builder.And(PredicateController.BlogCategory(category)); } var indexresults = context.GetQueryable <EntryResultItem>().Where(builder); if (indexresults.Any()) { result = indexresults.Select(i => new EntryItem(i.GetItem())).ToList(); result = result.OrderByDescending(post => post.Created).Take(maxNumber).ToList(); } } } #else var query = new CombinedQuery(); //query.Add(new FieldQuery(Constants.Index.Fields.BlogID, blog.ID.ToShortID().ToString().ToLower()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Path, customBlogItem.ID.ToShortID().ToString()), QueryOccurance.Must); query.Add(new FieldQuery(Constants.Index.Fields.Template, customBlogItem.BlogSettings.EntryTemplateID.ToShortID().ToString().ToLower()), QueryOccurance.Must); if (!string.IsNullOrEmpty(tag)) { query.Add(new FieldQuery(Constants.Index.Fields.Tags, DatabaseCrawler.TransformCSV(tag)), QueryOccurance.Must); } if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(blog, category); ID id = ID.Null; if (categoryItem != null) { id = categoryItem.ID; } query.Add(new FieldQuery(Constants.Index.Fields.Category, id.ToShortID().ToString().ToLower()), QueryOccurance.Must); } if (!string.IsNullOrEmpty(datePrefix)) { query.Add(new FieldQuery(Constants.Index.Fields.Created, datePrefix + "*"), QueryOccurance.Must); } var searcher = new Searcher(); result = searcher.Execute <EntryItem>(query, maxNumber, (list, item) => list.Add((EntryItem)item), Constants.Index.Fields.EntryDate, true).ToList(); #endif return(result.ToArray()); }
/// <summary> /// Gets blog entries for the given blog up to the maximum number given /// </summary> /// <param name="blog">The blog item to get the entries for</param> /// <param name="maxNumber">The maximum number of entries to retrieve</param> /// <param name="tag">A tag the entry must contain</param> /// <param name="category">A category the entry must contain</param> /// <returns></returns> public EntryItem[] GetBlogEntries(Item blog, int maxNumber, string tag, string category, string datePrefix = null) { if (blog == null || maxNumber <= 0) { return new EntryItem[0]; } BlogHomeItem customBlogItem = null; if (blog.TemplateIsOrBasedOn(Settings.BlogTemplateID)) { customBlogItem = blog; } else { customBlogItem = blog.GetCurrentItem(Settings.BlogTemplateIDString); } if (customBlogItem == null) { return new EntryItem[0]; } List<EntryItem> result = new List<EntryItem>(); #if FEATURE_CONTENT_SEARCH var indexName = Settings.SearchIndexName; if (!string.IsNullOrEmpty(indexName)) { using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext()) { var builder = PredicateBuilder.True<EntryResultItem>(); var id = Settings.EntryTemplateID; builder = builder.And(i => i.TemplateId==id); // Tag if (!String.IsNullOrEmpty(tag)) { builder = builder.And(PredicateController.BlogTags(tag)); } // Categories if (!string.IsNullOrEmpty(category)) { builder = builder.And(PredicateController.BlogCategory(category)); } var indexresults = context.GetQueryable<EntryResultItem>().Where(builder); if (indexresults.Any()) { result = indexresults.Select(i => new EntryItem(i.GetItem())).ToList(); result = result.OrderByDescending(post => post.Created).Take(maxNumber).ToList(); } } } #else var query = new CombinedQuery(); //query.Add(new FieldQuery(Constants.Index.Fields.BlogID, blog.ID.ToShortID().ToString().ToLower()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Path, customBlogItem.ID.ToShortID().ToString()), QueryOccurance.Must); query.Add(new FieldQuery(Constants.Index.Fields.Template, customBlogItem.BlogSettings.EntryTemplateID.ToShortID().ToString().ToLower()), QueryOccurance.Must); if (!string.IsNullOrEmpty(tag)) { query.Add(new FieldQuery(Constants.Index.Fields.Tags, DatabaseCrawler.TransformCSV(tag)), QueryOccurance.Must); } if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(blog, category); ID id = ID.Null; if (categoryItem != null) id = categoryItem.ID; query.Add(new FieldQuery(Constants.Index.Fields.Category, id.ToShortID().ToString().ToLower()), QueryOccurance.Must); } if (!string.IsNullOrEmpty(datePrefix)) { query.Add(new FieldQuery(Constants.Index.Fields.Created, datePrefix + "*"), QueryOccurance.Must); } var searcher = new Searcher(); result = searcher.Execute<EntryItem>(query, maxNumber, (list, item) => list.Add((EntryItem)item), Constants.Index.Fields.EntryDate, true).ToList(); #endif return result.ToArray(); }
public virtual List<SitecoreItem> GetItemsInRange(DateRangeSearchParam param) { var globalQuery = new CombinedQuery(); ApplyLanguageClause(globalQuery, param.Language); ApplyTemplateFilter(globalQuery, param.TemplateIds); ApplyLocationFilter(globalQuery, param.LocationIds); ApplyFullTextClause(globalQuery, param.FullTextQuery); ApplyRelationFilter(globalQuery, param.RelatedIds); var translator = new QueryTranslator(Index); var booleanQuery = translator.ConvertCombinedQuery(globalQuery); var innerOccurance = translator.GetOccur(param.Occurance); ApplyDateRangeSearchParam(booleanQuery, param, innerOccurance); return RunQuery(booleanQuery, param.ShowAllVersions); }
/// <summary> /// Gets blog entries for the given blog up to the maximum number given /// </summary> /// <param name="blog">The blog item to get the entries for</param> /// <param name="maxNumber">The maximum number of entries to retrieve</param> /// <param name="tag">A tag the entry must contain</param> /// <param name="category">A category the entry must contain</param> /// <param name="minimumDate">The minimum date for entries</param> /// <param name="maximumDate">The maximum date for the entries</param> /// <returns></returns> public EntryItem[] GetBlogEntries(Item blog, int maxNumber, string tag, string category, DateTime? minimumDate = null, DateTime? maximumDate = null) { if (blog == null || maxNumber <= 0) { return new EntryItem[0]; } BlogHomeItem customBlogItem = null; if (blog.TemplateIsOrBasedOn(Settings.BlogTemplateID)) { customBlogItem = blog; } else { customBlogItem = blog.GetCurrentItem(Settings.BlogTemplateIDString); } if (customBlogItem == null) { return new EntryItem[0]; } List<EntryItem> result = new List<EntryItem>(); #if FEATURE_CONTENT_SEARCH var indexName = Settings.SearchIndexName; if (!string.IsNullOrEmpty(indexName)) { using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck)) { var builder = PredicateBuilder.True<EntryResultItem>(); var id = customBlogItem.BlogSettings.EntryTemplateID; builder = builder.And(i => i.TemplateId == id); builder = builder.And(i => i.Paths.Contains(customBlogItem.ID)); builder = builder.And(i => i.Language.Equals(customBlogItem.InnerItem.Language.Name, StringComparison.InvariantCulture)); builder = builder.And(item => item.DatabaseName.Equals(Context.Database.Name, StringComparison.InvariantCulture)); // Tag if (!string.IsNullOrEmpty(tag)) { builder = builder.And(i => i.Tags.Contains(tag)); } // Categories if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(customBlogItem, category); // If the category is unknown, don't return any results. if (categoryItem == null) return new EntryItem[0]; #if SC70 var normalizedID = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(categoryItem.ID); builder = builder.And(i => i.Category.Contains(normalizedID)); #else builder = builder.And(i => i.Category.Contains(categoryItem.ID)); #endif } if (minimumDate != null) builder = builder.And(i => i.CreatedDate >= minimumDate); if(maximumDate != null) builder = builder.And(i => i.CreatedDate < maximumDate); var indexresults = context.GetQueryable<EntryResultItem>().Where(builder); if (indexresults.Any()) { result = indexresults.Select(i => new EntryItem(i.GetItem())).ToList(); result = result.OrderByDescending(post => post.EntryDate.DateTime).Take(maxNumber).ToList(); } } } #else var query = new CombinedQuery(); //query.Add(new FieldQuery(Constants.Index.Fields.BlogID, blog.ID.ToShortID().ToString().ToLower()), QueryOccurance.Must); query.Add(new FieldQuery(Sitecore.Search.BuiltinFields.Path, customBlogItem.ID.ToShortID().ToString()), QueryOccurance.Must); query.Add(new FieldQuery(Constants.Index.Fields.Template, customBlogItem.BlogSettings.EntryTemplateID.ToShortID().ToString().ToLower()), QueryOccurance.Must); if (!string.IsNullOrEmpty(tag)) { query.Add(new FieldQuery(Constants.Index.Fields.Tags, DatabaseCrawler.TransformCSV(tag)), QueryOccurance.Must); } if (!string.IsNullOrEmpty(category)) { var categoryItem = ManagerFactory.CategoryManagerInstance.GetCategory(blog, category); ID id = ID.Null; // If the category is unknown, don't return any results. if (categoryItem == null) return new EntryItem[0]; id = categoryItem.ID; query.Add(new FieldQuery(Constants.Index.Fields.Category, id.ToShortID().ToString().ToLower()), QueryOccurance.Must); } if (minimumDate != null) query.Add(new FieldQuery(Constants.Index.Fields.Created, minimumDate.Value.Year.ToString() + minimumDate.Value.Month.ToString() + "*"), QueryOccurance.Must); var searcher = new Searcher(); result = searcher.Execute<EntryItem>(query, blog.Language, maxNumber, (list, item) => list.Add((EntryItem)item), Constants.Index.Fields.EntryDate, false).ToList(); #endif return result.ToArray(); }
protected void ApplyLanguageClause(CombinedQuery query, string language) { if (String.IsNullOrEmpty(language)) return; query.Add(new FieldQuery(BuiltinFields.Language, language.ToLowerInvariant()), QueryOccurance.Must); }