public ExcludedSearchCriteria(ISearchCriteria searchCriteria) { if (searchCriteria == null) throw new ArgumentNullException("searchCriteria"); this.searchCriteria = searchCriteria; }
public override ISearchResults Search(ISearchCriteria searchParams, int maxResults) { Enforcer.ArgumentNotNull(searchParams, "searchParams"); var luceneParams = searchParams as LuceneSearchCriteria; if (luceneParams == null) { throw new ArgumentException("Provided ISearchCriteria dos not match the allowed ISearchCriteria. Ensure you only use an ISearchCriteria created from the current SearcherProvider"); } //check if we are sorting on Score, if so we'll need to set a lucene config switch if (luceneParams.SortFields.Count == 0) { SetScoringBooleanQueryRewriteMethod(luceneParams.Query); } var searcher = GetSearcher(); if (searcher == null) { return(new EmptySearchResults()); } var pagesResults = new SearchResults(luceneParams.Query, luceneParams.SortFields, searcher, maxResults); return(pagesResults); }
protected IQueryable <TEntity> CreateQuery <TEntity>(ISearchCriteria <TEntity> criteria) where TEntity : T { return(CreateQuery <TEntity>() .FilterBy(criteria.All) .Order(criteria.Order) .Page(criteria.PageNumber, criteria.PageSize)); }
private VolumeItem[] _SearchItem(ISearchCriteria searchCriteria) { // TODO : check SQL output! implemetation was rewritten from scratch!! // TODO : VolumeDatabase shouln't hardcode fieldnames or tablenames //const string ORDER_FIELD = "Items.VolumeID"; // slows down searching drastically /*** build sql query ***/ string condition = searchCriteria.GetSqlSearchCondition(); if (condition.Length == 0) // e.g. empty SearchCriteriaGroup { throw new ArgumentException("SearchCriteria is empty", "searchCriteria"); } string sqlQuery; if ((searchCriteria.SearchCriteriaType & SearchCriteriaType.VolumeSearchCriteria) == SearchCriteriaType.VolumeSearchCriteria) { // searchriteria contains volume searchriteria -> join volumes table sqlQuery = string.Format("SELECT Items.* FROM Items, Volumes WHERE ({0}) AND (Items.VolumeID = Volumes.VolumeID);", condition); } else { //sqlQuery = string.Format("SELECT * FROM Items WHERE {0} ORDER BY {1};", condition, ORDER_FIELD); sqlQuery = string.Format("SELECT * FROM Items WHERE {0};", condition); } if (Global.EnableDebugging) { Debug.WriteLine(string.Format("_SearchItem() executes query: '{0}'", sqlQuery)); } return(QueryItems <VolumeItem>(sqlQuery, searchItemResultsLimit)); }
/// <summary> /// Initializes a new instance of the <see cref="SearchResults"/> class. /// </summary> /// <param name="reader">The reader.</param> /// <param name="hits">The hits.</param> /// <param name="criteria">The criteria.</param> public SearchResults(IndexReader reader, Hits hits, ISearchCriteria criteria) { _IndexReader = reader; _Hits = hits; _BaseQuery = criteria.Query; _SearchCriteria = criteria; }
private static void AddSortArgument(ISearchCriteria criteria, ArgMap arguments) { if (criteria.Sort == null) { return; } var searchSortFields = criteria.Sort.GetSort(); if (searchSortFields == null || searchSortFields.Length == 0) { return; } var builder = new StringBuilder(); foreach (var field in searchSortFields) { if (builder.Length > 0) { builder.Append(","); } builder.Append(field.FieldName).Append(" ").Append(field.IsDescending ? "desc" : "asc"); } arguments.Add("sort_by", builder.ToString()); }
public object BuildQuery <T>(string scope, ISearchCriteria criteria) where T : class { var queryBuilder = _luceneQueryBuilder.BuildQuery <T>(scope, criteria) as QueryBuilder; if (criteria is CatalogItemSearchCriteria || criteria is CategorySearchCriteria) { var query = queryBuilder.Query as BooleanQuery; var innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term("usergroups", "__null__")), Occur.SHOULD); var userName = _userNameResolver.GetCurrentUserName(); var userAccount = System.Threading.Tasks.Task.Factory.StartNew(s => ((ISecurityService)s).FindByNameAsync(userName, UserDetails.Reduced), _securityService, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); if (userAccount != null && !userAccount.MemberId.IsNullOrEmpty()) { var contact = _memberService.GetByIds(new[] { userAccount.MemberId }).FirstOrDefault(); if (contact != null) { if (!contact.Groups.IsNullOrEmpty()) { foreach (var userGroup in contact.Groups) { innerQuery.Add(new TermQuery(new Term("usergroups", userGroup.ToLowerInvariant())), Occur.SHOULD); } } } } query.Add(innerQuery, Occur.MUST); } return(queryBuilder); }
/// <summary> /// Searhes content /// </summary> /// <param name="criteria"></param> /// <param name="searchProvider"></param> /// <returns></returns> public dynamic Search(ISearchCriteria criteria, BaseSearchProvider searchProvider = null) { return(_dynamicContentQuery == null ? new DynamicPublishedContentList( TypedSearch(criteria, searchProvider)) : _dynamicContentQuery.Search(criteria, searchProvider)); }
/// <summary> /// Builds the query. /// </summary> /// <param name="criteria">The criteria.</param> /// <returns></returns> public virtual object BuildQuery(ISearchCriteria criteria) { var query = new BooleanQuery(); if (criteria.CurrentFilterValues != null) { for (var index = 0; index < criteria.CurrentFilterFields.Length; index++) { var filter = criteria.CurrentFilters.ElementAt(index); var value = criteria.CurrentFilterValues.ElementAt(index); var field = criteria.CurrentFilterFields.ElementAt(index); // Skip currencies that are not part of the filter if (filter.GetType() == typeof(PriceRangeFilter)) // special filtering { var currency = (filter as PriceRangeFilter).Currency; if (!currency.Equals(criteria.Currency, StringComparison.OrdinalIgnoreCase)) { continue; } } var filterQuery = filter.GetType() == typeof(PriceRangeFilter) ? LuceneQueryHelper.CreateQuery(criteria, field, value as RangeFilterValue) : LuceneQueryHelper.CreateQuery(field, value); if (filterQuery != null) { query.Add(filterQuery, Occur.MUST); } } } return query; }
protected Model(IDomainContext domainContext, ISearchCriteria searchCriteria) { DomainContext = domainContext; SearchCriteria = searchCriteria; entitiesIsLoaded = false; InitializeDataService(); }
/// <summary> /// Creates the query. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Filter CreateQuery(ISearchCriteria criteria, string field, RangeFilterValue value) { var query = new BooleanFilter(); object lowerbound = value.Lower; object upperbound = value.Upper; const bool lowerboundincluded = true; const bool upperboundincluded = false; var currency = criteria.Currency.ToLower(); var upper = upperbound == null?NumericUtils.LongToPrefixCoded(long.MaxValue) : ConvertToSearchable(upperbound); // format is "fieldname_store_currency_pricelist" string[] pls = null; var searchCriteria = criteria as CatalogIndexedSearchCriteria; if (searchCriteria != null) { pls = searchCriteria.Pricelists; } var parentPriceList = String.Empty; // Create filter of type // price_USD_pricelist1:[100 TO 200} (-price_USD_pricelist1:[* TO *} +(price_USD_pricelist2:[100 TO 200} (-price_USD_pricelist2:[* TO *} (+price_USD_pricelist3[100 TO 200})))) if (pls == null || !pls.Any()) { return(null); } var priceListId = pls[0].ToLower(); var filter = new TermRangeFilter( String.Format("{0}_{1}_{2}", field, currency, priceListId), ConvertToSearchable(lowerbound), upper, lowerboundincluded, upperboundincluded); query.Add(new FilterClause(filter, Occur.SHOULD)); if (pls.Count() > 1) { var q = CreatePriceRangeQuery( pls, 1, field, currency, ConvertToSearchable(lowerbound), upper, lowerboundincluded, upperboundincluded); query.Add(new FilterClause(q, Occur.SHOULD)); } return(query); }
void Initialize() { if (string.IsNullOrEmpty(SearchTerm)) { SearchResults = new List <SearchResult>(); return; } // Set indexed fields IndexedFields = _indexer.IndexerData.UserFields.Select(f => f.Name).ToList(); var searchCriteria = _searcher.CreateSearchCriteria(BooleanOperation.And).Field("robotsIndex", "0").Compile(); try { ISearchCriteria query = searchCriteria.RawQuery(CreateRawQuery()); var searchResults = _searcher.Search(query); // Set total result-count TotalResults = searchResults.TotalItemCount; // Skip, take and order var resultCollection = searchResults.OrderByDescending(x => x.Score).Skip(_skip).Take(_take); SearchResults = resultCollection.ToList(); } catch (Exception e) { } }
public static BoolFilter<ESDocument> CreateQueryForValue(ISearchCriteria criteria, ISearchFilter filter, ISearchFilterValue value) { var query = new BoolFilter<ESDocument>(); var field = filter.Key.ToLower(); if (filter.GetType() == typeof(PriceRangeFilter)) { var tempQuery = CreatePriceRangeFilter(criteria, field, value as RangeFilterValue); if (tempQuery != null) { query.Must(q => q.Bool(b => tempQuery)); } } else { if (value.GetType() == typeof(AttributeFilterValue)) { query.Must(q => q.Term(t=>t.Field(field).Value(((AttributeFilterValue)value).Value))); } else if (value.GetType() == typeof(RangeFilterValue)) { var tempValue = value as RangeFilterValue; var tempFilter = new RangeFilter<ESDocument>(); tempFilter.Field(field).From(tempValue.Lower).To(tempValue.Upper).IncludeLower(true).IncludeUpper(false); query.Should(q => q.Range(r => tempFilter)); } } return query; }
/// <summary> /// Performs a lucene search using Examine. /// </summary> /// <param name="documentTypes">Array of document type aliases to search for.</param> /// <param name="searchGroups">A list of search groupings, if you have more than one group it will apply an and to the search criteria</param> /// <returns>Examine search results</returns> public Examine.ISearchResults SearchUsingExamine(string[] documentTypes, List <SearchGroup> searchGroups) { ISearchCriteria searchCriteria = ExamineManager.Instance.CreateSearchCriteria(BooleanOperation.And); IBooleanOperation queryNodes = null; //only shows results for visible documents. queryNodes = searchCriteria.GroupedNot(new string[] { "umbracoNaviHide" }, "1"); if (documentTypes != null && documentTypes.Length > 0) { //only get results for documents of a certain type queryNodes = queryNodes.And().GroupedOr(new string[] { _docTypeAliasFieldName }, documentTypes); } if (searchGroups != null && searchGroups.Any()) { //in each search group it looks for a match where the specified fields contain any of the specified search terms //usually would only have 1 search group, unless you want to filter out further, i.e. using categories as well as search terms foreach (SearchGroup searchGroup in searchGroups) { queryNodes = queryNodes.And().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms); } } //return the results of the search return(ExamineManager.Instance.Search(queryNodes.Compile()));; }
/// <summary> /// Searches the datasource using the specified criteria. Criteria is parsed by the query builder specified by /// <typeparamref /> /// . /// </summary> /// <param name="scope">Name of the application.</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> /// <exception cref="VirtoCommerce.SearchModule.Data.Providers.Lucene.LuceneSearchException"></exception> public virtual ISearchResults Search(string scope, ISearchCriteria criteria) { ISearchResults result; var directoryInfo = new DirectoryInfo(GetDirectoryPath(GetFolderName(scope, criteria.DocumentType))); if (directoryInfo.Exists) { var dir = FSDirectory.Open(directoryInfo); var searcher = new IndexSearcher(dir); var q = (QueryBuilder)QueryBuilder.BuildQuery(criteria); // filter out empty value var filter = q.Filter.ToString().Equals("BooleanFilter()") ? null : q.Filter; Debug.WriteLine("Search Lucene Query:{0}", q.ToString()); TopDocs docs; try { var numDocs = criteria.StartingRecord + criteria.RecordsToRetrieve; if (criteria.Sort != null) { var fields = criteria.Sort.GetSort(); docs = searcher.Search( q.Query, filter, numDocs, new Sort( fields.Select(field => new SortField(field.FieldName, field.DataType, field.IsDescending)) .ToArray())); } else { docs = searcher.Search(q.Query, filter, numDocs); } } catch (Exception ex) { throw new LuceneSearchException("Search exception", ex); } var results = new LuceneSearchResults(searcher, searcher.IndexReader, docs, criteria, q.Query); // Cleanup here searcher.IndexReader.Dispose(); searcher.Dispose(); result = results.Results; } else { result = new SearchResults(criteria, null); } return(result); }
public static List <IParty> GetParty(int PartyID, ISearchCriteria searchCriteria) { string strExecution = "[fwd].[uspGetParty]"; List <IParty> lstParty = new List <IParty>(); using (DbQuery oDq = new DbQuery(strExecution)) { oDq.AddBigIntegerParam("@PartyId", PartyID); oDq.AddVarcharParam("@SchLocAbbr", 3, searchCriteria.LocAbbr); oDq.AddVarcharParam("@SchPartyName", 60, searchCriteria.PartyName); oDq.AddVarcharParam("@SchShortName", 10, searchCriteria.StringParams[1]); oDq.AddIntegerParam("@SchPartyType", Convert.ToInt32(searchCriteria.StringParams[0])); oDq.AddVarcharParam("@SortExpression", 50, searchCriteria.SortExpression); oDq.AddVarcharParam("@SortDirection", 4, searchCriteria.SortDirection); DataSet reader = oDq.GetTables(); if (reader != null && reader.Tables.Count > 0 && reader.Tables[0].Rows.Count > 0) { for (int i = 0; i < reader.Tables[0].Rows.Count; i++) { IParty iParty = new PartyEntity(reader.Tables[0].Rows[i]); lstParty.Add(iParty); } } } return(lstParty); }
public async Task <IEnumerable <T> > Search(ISearchCriteria criteria = null, FilterDefinition <T> filter = null) { if (filter == null) { return(null); } if (criteria == null) { criteria = new SearchCriteria(); } try { return(await collection .Find(filter) .Skip(criteria.Offset) .Limit(criteria.Limit) .ToListAsync()); } catch (Exception ex) { throw ex; } }
public override ISearchResults Search(string applicationName, ISearchCriteria criteria) { if (criteria is CatalogEntrySearchCriteria) { var cesc = criteria as CatalogEntrySearchCriteria; if (cesc.ClassTypes != null && cesc.ClassTypes.Count == 1) { // in this provider, we only support a single class type switch (cesc.ClassTypes[0].ToUpper()) { case "VARIANT": return(Search <VariationContent>(criteria)); case "PRODUCT": return(Search <ProductContent>(criteria)); case "BUNDLE": return(Search <BundleContent>(criteria)); case "PACKAGE": case "DYNAMICPACKAGE": // for Vulcan purposes, dynamic packages are the same as packages return(Search <PackageContent>(criteria)); } } } return(Search <EntryContentBase>(criteria)); }
///<summary> /// Queries eSales based on the criteria. ///</summary> ///<param name="applicationName">The application name for the query.</param> ///<param name="criteria">The search criteria.</param> ///<returns>Search results, including a product count, product listing and navigation panel.</returns> ///<exception cref="ProviderException">If the application name does not match the application name configured for eSales.</exception> public override ISearchResults Search(string applicationName, ISearchCriteria criteria) { criteria.Locale = criteria.Locale.ToESalesLocale(); var pc = PerformQuery(criteria); return(pc == null ? new ESalesSearchResult(criteria) : new ESalesSearchResult(_configuration, pc, criteria)); }
/// <summary> /// Gets a subset of search results to search in based on the current criteria /// </summary> /// <param name="criteriaSet"></param> /// <returns>Search subset</returns> protected virtual SearchSubset GetSearchSubset(SearchCriteriaSet criteriaSet) { ICacheable finalEntry = null; int hashSum = criteriaSet.DescriptionFilter.GetHashCode(); int i, n = criteriaSet.Count; for (i = 0; i < n; i++) { ISearchCriteria criteria = criteriaSet[i]; //combine the current hash with the pervious hash hashSum = hashSum ^ criteria.GetHashCode(); //check if a subset is cached for this hash ICacheable entry = SearchSubsetsCache.Instance.GetEntry(hashSum); if (entry != null) { criteriaSet.StartCriteriaIndex = i; finalEntry = entry; } else { break; } } SearchSubset subset = null; if (finalEntry != null) { subset = finalEntry.GetClone() as SearchSubset; } return(subset); }
public static BoolFilter <ESDocument> CreateQueryForValue(ISearchCriteria criteria, ISearchFilter filter, ISearchFilterValue value) { var query = new BoolFilter <ESDocument>(); var field = filter.Key.ToLower(); if (filter.GetType() == typeof(PriceRangeFilter)) { var tempQuery = CreatePriceRangeFilter(criteria, field, value as RangeFilterValue); if (tempQuery != null) { query.Must(q => q.Bool(b => tempQuery)); } } else { if (value.GetType() == typeof(AttributeFilterValue)) { query.Must(q => q.Term(t => t.Field(field).Value(((AttributeFilterValue)value).Value))); } else if (value.GetType() == typeof(RangeFilterValue)) { var tempValue = value as RangeFilterValue; var tempFilter = new RangeFilter <ESDocument>(); tempFilter.Field(field).From(tempValue.Lower).To(tempValue.Upper).IncludeLower(true).IncludeUpper(false); query.Should(q => q.Range(r => tempFilter)); } } return(query); }
/// <summary> /// Initializes a new instance of the <see cref="SearchResults" /> class. /// </summary> /// <param name="searcher">The searcher.</param> /// <param name="reader">The reader.</param> /// <param name="docs">The hits.</param> /// <param name="criteria">The criteria.</param> /// <param name="query">The query.</param> public LuceneSearchResults(Searcher searcher, IndexReader reader, TopDocs docs, ISearchCriteria criteria, Query query) { Results = new SearchResults(criteria, null); CreateDocuments(searcher, docs); CreateFacets(reader, query); CreateSuggestions(reader, criteria); }
/// <summary> /// queries the Lucene index to get all members with the supplied partyGuid /// </summary> /// <param name="members">the Umbraco MembershipHelper</param> /// <param name="partyGuid">Guid identifying a specific party</param> /// <returns>a collection of PartyHost / PartyGuest associated with a specific party</returns> public static IEnumerable <IPartier> GetPartiers(this MembershipHelper members, Guid partyGuid) { BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"]; ISearchCriteria searchCriteria = searchProvider.CreateSearchCriteria(IndexTypes.Member).Field("partyGuid", partyGuid.ToString()).Compile(); ISearchResults searchResults = searchProvider.Search(searchCriteria); return(searchResults.Select(x => (IPartier)members.GetById(x.Id))); }
public CatalogItemSearchResults(ISearchCriteria criteria, Dictionary<string, Dictionary<string, object>> items, SearchResults results) { _Items = items; _TotalCount = results.TotalCount; _Count = results.DocCount; _FacetGroups = results.FacetGroups; _SearchCriteria = criteria; }
/// <summary> /// Initializes a new instance of the <see cref="SearchResults" /> class. /// </summary> /// <param name="searcher">The searcher.</param> /// <param name="reader">The reader.</param> /// <param name="docs">The hits.</param> /// <param name="criteria">The criteria.</param> /// <param name="query">The query.</param> public LuceneSearchResults( Searcher searcher, IndexReader reader, TopDocs docs, ISearchCriteria criteria, Query query) { Results = new SearchResults(criteria, null); CreateDocuments(searcher, docs); CreateFacets(reader, query); CreateSuggestions(reader, criteria); }
public OrderSearchResults(ISearchCriteria criteria, OrderGroup[] orders, SearchResults results) { _OrderGroups = orders; _TotalCount = results.TotalCount; _Count = results.DocCount; _FacetGroups = results.FacetGroups; _SearchCriteria = criteria; }
public Request(ISearchCriteria criteria, int depth, ReceiveResponse callback) { Identifier = Environment.MachineName + Peer.Self.Name + DateTime.UtcNow; SearchCriteria = criteria; Requester = Peer.Self; Depth = depth; Callback = callback; }
public CatalogItemSearchResults(ISearchCriteria criteria, Dictionary <string, Dictionary <string, object> > items, SearchResults results) { _Items = items; _TotalCount = results.TotalCount; _Count = results.DocCount; _FacetGroups = results.FacetGroups; _SearchCriteria = criteria; }
private static string ReplaceWithLocationData(this string input, ISearchCriteria data) { if (input.IsNullOrEmpty()) { return(string.Empty); } return(input.Replace("{STATE}", LocationBc.Instance.GetStateName(data.StateCode())).Replace("{STATE_CODE}", data.StateCode()).Replace("{CITY}", data.City())); }
public static Estimate GetEstimate(ISearchCriteria searchCriteria) { Estimate estimate = null; string strExecution = "[fwd].[spGetEstimate]"; DataSet reader = new DataSet(); using (DbQuery oDq = new DbQuery(strExecution)) { oDq.AddIntegerParam("@pk_EstimateID", Convert.ToInt32(searchCriteria.StringOption1)); int result = 0; oDq.AddIntegerParam("@Result", result, QueryParameterDirection.Output); reader = oDq.GetTables(); if (reader != null && reader.Tables.Count > 1) { var tblEst = reader.Tables[0].AsEnumerable().Select(x => new Estimate { PorR = Convert.ToString(x["PorR"].GetType() == typeof(DBNull) ? "" : x["PorR"]), EstimateNo = Convert.ToString(x["EstimateNo"].GetType() == typeof(DBNull) ? "" : x["EstimateNo"]), EstimateDate = Convert.ToDateTime(x["EstimateDate"].GetType() == typeof(DBNull) ? (DateTime?)null : x["EstimateDate"]), TransactionType = Convert.ToString(x["TransactionType"].GetType() == typeof(DBNull) ? "" : x["TransactionType"]), BillFromId = Convert.ToInt32(x["fk_BillFromID"].GetType() == typeof(DBNull) ? 0 : x["fk_BillFromID"]), CreditDays = Convert.ToInt32(x["CreditDays"].GetType() == typeof(DBNull) ? 0 : x["CreditDays"]), JobNo = Convert.ToString(x["JobNo"].GetType() == typeof(DBNull) ? "" : x["JobNo"]), PartyId = Convert.ToInt32(x["fk_PartyID"].GetType() == typeof(DBNull) ? 0 : x["fk_PartyID"]), PartyTypeId = Convert.ToInt32(x["PartyTypeID"].GetType() == typeof(DBNull) ? 0 : x["PartyTypeID"]), PartyName = Convert.ToString(x["PartyName"].GetType() == typeof(DBNull) ? "" : x["PartyName"]), UnitTypeId = Convert.ToInt32(x["fk_UnitTypeID"].GetType() == typeof(DBNull) ? 0 : x["fk_UnitTypeID"]), JobID = Convert.ToInt32(x["fk_JobID"].GetType() == typeof(DBNull) ? 0 : x["fk_JobID"]), ROE = Convert.ToDecimal(x["ROE"].GetType() == typeof(DBNull) ? 0 : x["ROE"]), JobActive = Convert.ToString(x["JobActive"].GetType() == typeof(DBNull) ? 0 : x["JobActive"]) }); estimate = tblEst.FirstOrDefault(); estimate.Charges = reader.Tables[1].AsEnumerable().Select(x => new Charge { ChargeId = Convert.ToInt32(x["pk_ChargeRateID"].GetType() == typeof(DBNull) ? 0 : x["pk_ChargeRateID"]), Unit = Convert.ToDouble(x["Nos"].GetType() == typeof(DBNull) ? 0 : x["Nos"]), ChargeMasterId = Convert.ToInt32(x["fk_ChargeID"].GetType() == typeof(DBNull) ? 0 : x["fk_ChargeID"]), ChargeMasterName = Convert.ToString(x["ChargeIDName"].GetType() == typeof(DBNull) ? "" : x["ChargeIDName"]), CntrSize = Convert.ToString(x["CntrSize"].GetType() == typeof(DBNull) ? "" : x["CntrSize"]), CurrencyId = Convert.ToInt32(x["fk_CurrencyID"].GetType() == typeof(DBNull) ? 0 : x["fk_CurrencyID"]), Currency = Convert.ToString(x["CurrencyName"].GetType() == typeof(DBNull) ? "" : x["CurrencyName"]), ROE = Convert.ToDouble(x["ROE"].GetType() == typeof(DBNull) ? 0 : x["ROE"]), Rate = Convert.ToDouble(x["ChargeAmount"].GetType() == typeof(DBNull) ? 0 : x["ChargeAmount"]), INR = Convert.ToDouble(x["INRAmount"].GetType() == typeof(DBNull) ? 0 : x["INRAmount"]), STax = Convert.ToDouble(x["StaxAmount"].GetType() == typeof(DBNull) ? 0 : x["StaxAmount"]), //UnitType = Convert.ToString(x["UnitType"].GetType() == typeof(DBNull) ? 0 : x["UnitType"]), UnitType = Convert.ToString(x["ContainerAbbr"].GetType() == typeof(DBNull) ? 0 : x["ContainerAbbr"]), UnitId = Convert.ToInt32(x["fk_UnitTypeID"].GetType() == typeof(DBNull) ? 0 : x["fk_UnitTypeID"]), ChargeType = Convert.ToString(x["ChargeType"].GetType() == typeof(DBNull) ? 0 : x["ChargeType"]), }).ToList(); } } return(estimate); }
public OrderSearchResults SearchOrders(string scope, ISearchCriteria criteria) { OrderGroup[] resultItems; var orderCriteria = criteria as OrderSearchCriteria; System.Threading.Thread.Sleep(100); var query = MockOrderList.Select(a => a); //var query = from item in MockOrderList // select item; int totalCount = MockOrderList.Count; if (orderCriteria != null) { if (orderCriteria.Sort != null) { if (orderCriteria.Sort.GetSort()[0].IsDescending) { query = query.OrderByDescending(x => x.Total); } else { query = query.OrderBy(x => x.Total); } } if (!string.IsNullOrEmpty(orderCriteria.OrderStatus)) { query = query.Where(x => x.Status == orderCriteria.OrderStatus); } if (!string.IsNullOrEmpty(orderCriteria.TrackingNumber)) { query = query.Where(x => x.TrackingNumber.Contains(orderCriteria.TrackingNumber)); } if (!string.IsNullOrEmpty(orderCriteria.CustomerEmail)) { query = query.Where(x => (x.OrderAddresses.Select(b => b.Email.StartsWith(orderCriteria.CustomerEmail)).Count()) > 0); } if (!string.IsNullOrEmpty(orderCriteria.CustomerId)) { query = query.Where(x => x.CustomerId == orderCriteria.CustomerId); } if (!string.IsNullOrEmpty(orderCriteria.Keyword)) { query = query.Where(x => x.TrackingNumber == orderCriteria.Keyword); } totalCount = query.Count(); query = query.Skip(criteria.StartingRecord).Take(criteria.RecordsToRetrieve); } resultItems = query.ToArray(); MockSearchResults searchResults = new MockSearchResults(criteria, resultItems.Length, totalCount); var retVal = new OrderSearchResults(criteria, resultItems, searchResults); return(retVal); }
private static string GetLuceneQuery(ISearchCriteria searchCriteria) { // this line can be used when examine dependency is updated //if (searchCriteria is LuceneSearchCriteria criteria) return criteria.Query?.ToString(); var query = Regex.Match(searchCriteria.ToString(), "LuceneQuery: (.*) }"); return(query.Success && query.Groups.Count > 0 ? query.Groups[1].Value : string.Empty);; }
public ExcludedSearchCriteria(ISearchCriteria searchCriteria) { if (searchCriteria == null) { throw new ArgumentNullException("searchCriteria"); } this.searchCriteria = searchCriteria; }
public IList <User> GetByPredicate(ISearchCriteria <User> predicate) { if (predicate == null) { throw new ArgumentNullException($"{nameof(predicate)} argument null"); } return(this.repository.GetByPredicate(predicate.IsMatch)); }
private static Expression <Func <T, bool> > GetFilter <T>(ISearchCriteria searchExpression) { var type = typeof(T); var argParam = Expression.Parameter(type, "p"); var expression = searchExpression.GetFilter(argParam); var filter = Expression.Lambda <Func <T, bool> >(expression, argParam); return(filter); }
/// <summary> /// Initializes a new instance of the <see cref="SearchCriteriaViewModel"/> class. /// </summary> /// <param name="criterea">The criterea.</param> public SearchCriteriaViewModel(ISearchCriteria criterea) { if (criterea != null) { this.SearchFor = criterea.SearchFor; this.CategoryID = criterea.CategoryID; this.OSID = criterea.OSID; this.OrderBy = criterea.OrderBy; this.Page = 1; //todo: add additional criterea here } }
public static Filter CreateQuery(ISearchCriteria criteria, ISearchFilter filter, Occur clause) { var values = GetFilterValues(filter); if (values == null) return null; var query = new BooleanFilter(); foreach (var value in values) { var valueQuery = CreateQueryForValue(criteria, filter, value); query.Add(new FilterClause(valueQuery, Occur.SHOULD)); } return query; }
public OrderSearchResults SearchOrders(string scope, ISearchCriteria criteria) { var results = _searchService.Search(scope, criteria) as SearchResults; if (results != null) { var resultIds = results.GetKeyFieldValues<string>(); var orders = _orderRepository.Orders.Where(x => resultIds.Contains(x.OrderGroupId)).ToArray(); var retVal = new OrderSearchResults(criteria, orders, results); return retVal; } return null; }
public static BoolFilter<ESDocument> CreateQuery(ISearchCriteria criteria, ISearchFilter filter) { var values = GetFilterValues(filter); if (values == null) return null; var query = new BoolFilter<ESDocument>(); foreach (var value in values) { var valueQuery = CreateQueryForValue(criteria, filter, value); //var boolQuery = new Query<ESDocument>(); //boolQuery.Bool(x => valueQuery); query.Should(x=>x.Bool(y=>valueQuery)); } return query; }
public ISearchResults Search(string scope, ISearchCriteria criteria) { // Build query var builder = (SearchQuery)_queryBuilder.BuildQuery(criteria); SearchQueryResult resultDocs; // Add some error handling //try { var searchResponse = Client.Search(scope, builder).Result; if (!searchResponse.IsSuccess) { throw new AzureSearchException(AzureSearchHelper.FormatSearchException(searchResponse)); } resultDocs = searchResponse.Body; } /* catch (Exception ex) { throw ex; } * */ // Parse documents returned var documents = new ResultDocumentSet { TotalCount = resultDocs.Count }; var docList = new List<ResultDocument>(); foreach (var indexDoc in resultDocs.Records) { var document = new ResultDocument(); foreach (var field in indexDoc.Properties.Keys) { document.Add(new DocumentField(field, indexDoc.Properties[field])); } docList.Add(document); } documents.Documents = docList.ToArray(); // Create search results object var results = new SearchResults(criteria, new[] { documents }); return results; }
/// <summary> /// Creates the price range filter. /// </summary> /// <param name="criteria">The criteria.</param> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static BoolFilter<ESDocument> CreatePriceRangeFilter(ISearchCriteria criteria, string field, RangeFilterValue value) { var query = new BoolFilter<ESDocument>(); var lowerbound = value.Lower; var upperbound = value.Upper; var lowerboundincluded = true; var upperboundincluded = false; var currency = criteria.Currency.ToLower(); // format is "fieldname_store_currency_pricelist" string[] pls = null; if (criteria is CatalogItemSearchCriteria) { pls = ((CatalogItemSearchCriteria)criteria).Pricelists; } var parentPriceList = String.Empty; // Create filter of type // price_USD_pricelist1:[100 TO 200} (-price_USD_pricelist1:[* TO *} +(price_USD_pricelist2:[100 TO 200} (-price_USD_pricelist2:[* TO *} (+price_USD_pricelist3[100 TO 200})))) if (pls == null || pls.Count() == 0) return null; var priceListId = pls[0].ToLower(); var filter = new RangeFilter<ESDocument>(); filter.Field(String.Format("{0}_{1}_{2}", field, currency, priceListId)).From(lowerbound).To(upperbound).IncludeLower(lowerboundincluded).IncludeUpper(upperboundincluded); //query.Should(q => q.ConstantScore(c => c.Filter(f => f.Range(r => filter)))); query.Should(q => q.Range(r => filter)); if (pls.Count() > 1) { var temp = CreatePriceRangeFilter(pls, 1, field, currency, lowerbound, upperbound, lowerboundincluded, upperboundincluded); query.Should(q => q.Bool(b => temp)); } //Query query = new ConstantScoreQuery(filter); return query; }
public static Filter CreateQueryForValue(ISearchCriteria criteria, ISearchFilter filter, ISearchFilterValue value) { Filter q = null; var priceQuery = filter is PriceRangeFilter; if (value is RangeFilterValue && priceQuery) { q = LuceneQueryHelper.CreateQuery( criteria, filter.Key, value as RangeFilterValue); } else if (value is CategoryFilterValue) { q = CreateQuery(filter.Key, value as CategoryFilterValue); } else { q = CreateQuery(filter.Key, value); } return q; }
public static Filter CreateQueryForValue(ISearchCriteria criteria, ISearchFilter filter, ISearchFilterValue value) { Filter q; var priceQuery = filter is PriceRangeFilter; var rangeFilterValue = value as RangeFilterValue; if (rangeFilterValue != null && priceQuery) { q = CreateQuery(criteria, filter.Key, rangeFilterValue); } else if (value is CategoryFilterValue) { q = CreateQuery(filter.Key, (CategoryFilterValue)value); } else { q = CreateQuery(filter.Key, value); } return q; }
public static ISearchCriteria BuildQuery(string[] textFields, string searchString, ISearchCriteria criteria) { List<SearchTerm> Terms = new List<SearchTerm>(); if ((searchString.Contains(@"""")) && (searchString.Count(t => t == '"') % 2 == 0)) // even number of quotes, more than zero { Regex quoteRegex = new Regex(@""".+?"""); // look for any content between quotes foreach (Match item in quoteRegex.Matches(searchString)) { Terms.Add(new SearchTerm() { Term = item.Value.Replace('"', ' ').Trim(), TermType = SearchTermType.MultiWord }); searchString = Regex.Replace(searchString, item.Value, string.Empty); // remove them from search string for subsequent parsing } } List<string> singleTerms = new List<string>(); singleTerms = searchString.Split(' ').ToList(); singleTerms.ForEach(t => Terms.Add(new SearchTerm() { Term = t, TermType = SearchTermType.SingleWord })); foreach (SearchTerm t in Terms) { if (!string.IsNullOrEmpty(t.Term)) { switch (t.TermType) { case SearchTermType.SingleWord: criteria.GroupedOr(textFields, new IExamineValue[] { Examine.LuceneEngine.SearchCriteria.LuceneSearchExtensions.Fuzzy(t.Term, 0.4F) }); break; case SearchTermType.MultiWord: criteria.GroupedOr(textFields, new IExamineValue[] { Examine.LuceneEngine.SearchCriteria.LuceneSearchExtensions.Escape(t.Term) }); break; default: break; } } } return criteria; }
public static ISearchCriteria BuildQuery(string searchString, ISearchCriteria criteria, string[] textFields) { var terms = searchString.ToSearchTerms(); foreach (var t in terms.Where(t => !string.IsNullOrEmpty(t.Term))) { switch (t.SearchTermType) { case SearchTermType.SingleWord: criteria.GroupedOr( textFields, new[] { t.Term.Fuzzy() }); break; case SearchTermType.MultiWord: criteria.GroupedOr( textFields, new[] { t.Term.MultipleCharacterWildcard() }); break; } } return criteria; }
/// <summary> /// Initializes a new instance of the <see cref="SearchResult"/> class. /// </summary> /// <param name="criterea">The criterea.</param> /// <param name="page">The page.</param> internal SearchResult(ISearchCriteria criterea = null, int page = 1) { this.Criterea = criterea; using (var context = Connection.GetContext()) { IQueryable<Persistence.App> query = context .Apps .Include("Pictures") .Include("Categories") .Include("OperatingSystems") .Include("Recentions") .Include("Recentions.User") .Include("Producer"); if (criterea != null) { query = QueryByCriterea(query, criterea); } this.ResultAppCount = query.Count(); this.Page = page <= Pages && page > 0 ? page : 1; if (criterea != null) { query = query.SortByCritera(criterea); } else { query = query.SortByCritera(); } query = query.Skip(APPSPERPAGE * (this.Page - 1)).Take(APPSPERPAGE); List<IApp> result = new List<IApp>(); foreach (var item in query) { result.Add(new App(item)); } this.Apps = result.ToArray(); } }
/// <summary> /// Builds the query. /// </summary> /// <param name="criteria">The criteria.</param> /// <returns></returns> public virtual object BuildQuery(ISearchCriteria criteria) { var queryBuilder = new QueryBuilder(); var queryFilter = new BooleanFilter(); var query = new BooleanQuery(); queryBuilder.Query = query; queryBuilder.Filter = queryFilter; if (criteria.CurrentFilters != null) { foreach (var filter in criteria.CurrentFilters) { // Skip currencies that are not part of the filter if (filter.GetType() == typeof(PriceRangeFilter)) // special filtering { var currency = (filter as PriceRangeFilter).Currency; if (!currency.Equals(criteria.Currency, StringComparison.OrdinalIgnoreCase)) { continue; } } var filterQuery = LuceneQueryHelper.CreateQuery(criteria, filter, Occur.SHOULD); // now add other values that should also be counted? if (filterQuery != null) { var clause = new FilterClause(filterQuery, Occur.MUST); queryFilter.Add(clause); } } } return queryBuilder; }
/// <summary> /// Searches InvoiceIndex using <see cref="ISearchCriteria"/> passed /// </summary> /// <param name="criteria"> /// The criteria. /// </param> /// <returns> /// A collection of <see cref="InvoiceDisplay"/> /// </returns> public static IEnumerable<InvoiceDisplay> Search(ISearchCriteria criteria) { return ExamineManager.Instance.SearchProviderCollection[SearcherName] .Search(criteria).OrderByDescending(x => x.Score) .Select(result => result.ToInvoiceDisplay(OrderQuery.GetByInvoiceKey)); }
/// <summary> /// Searches the datasource using the specified criteria. Criteria is parsed by the query builder specified by /// <typeparamref /> /// . /// </summary> /// <param name="scope">Name of the application.</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> /// <exception cref="VirtoCommerce.SearchModule.Data.Providers.Lucene.LuceneSearchException"></exception> public virtual ISearchResults Search(string scope, ISearchCriteria criteria) { ISearchResults result; var directoryInfo = new DirectoryInfo(GetDirectoryPath(GetFolderName(scope, criteria.DocumentType))); if (directoryInfo.Exists) { var dir = FSDirectory.Open(directoryInfo); var searcher = new IndexSearcher(dir); var q = (QueryBuilder)QueryBuilder.BuildQuery(criteria); // filter out empty value var filter = q.Filter.ToString().Equals("BooleanFilter()") ? null : q.Filter; Debug.WriteLine("Search Lucene Query:{0}", q.ToString()); TopDocs docs; try { var numDocs = criteria.StartingRecord + criteria.RecordsToRetrieve; if (criteria.Sort != null) { var fields = criteria.Sort.GetSort(); docs = searcher.Search( q.Query, filter, numDocs, new Sort( fields.Select(field => new SortField(field.FieldName, field.DataType, field.IsDescending)) .ToArray())); } else { docs = searcher.Search(q.Query, filter, numDocs); } } catch (Exception ex) { throw new LuceneSearchException("Search exception", ex); } var results = new LuceneSearchResults(searcher, searcher.IndexReader, docs, criteria, q.Query); // Cleanup here searcher.IndexReader.Dispose(); searcher.Dispose(); result = results.Results; } else { result = new SearchResults(criteria, null); } return result; }
/// <summary> /// Searches the datasource using the specified criteria. Criteria is parsed by the query builder specified by /// <typeparamref /// name="QueryBuilderType" /> /// . /// </summary> /// <param name="scope">Name of the application.</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> /// <exception cref="VirtoCommerce.Search.Providers.Lucene.LuceneSearchException"></exception> public virtual ISearchResults Search(string scope, ISearchCriteria criteria) { TopDocs docs = null; var folderName = this.GetFolderName(scope, criteria.DocumentType); var dir = FSDirectory.Open(new DirectoryInfo(this.GetDirectoryPath(folderName))); var searcher = new IndexSearcher(dir); var q = (Query)this.QueryBuilder.BuildQuery(criteria); Debug.WriteLine("Search Lucene Query:{0}", (object)q.ToString()); try { var numDocs = criteria.StartingRecord + criteria.RecordsToRetrieve; if (criteria.Sort != null) { var fields = criteria.Sort.GetSort(); docs = searcher.Search( q, null, numDocs, new Sort( fields.Select(field => new SortField(field.FieldName, field.DataType, field.IsDescending)) .ToArray())); } else { docs = searcher.Search(q, numDocs); } } catch (Exception ex) { throw new LuceneSearchException("Search exception", ex); } var results = new LuceneSearchResults(searcher, searcher.IndexReader, docs, criteria, q); // Cleanup here searcher.IndexReader.Dispose(); searcher.Dispose(); return results.Results; }
public ISearchResults Search(string scope, ISearchCriteria criteria) { return CurrentProvider.Search(scope, criteria); }
/// <summary> /// Creates the query. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Filter CreateQuery(ISearchCriteria criteria, string field, RangeFilterValue value) { var query = new BooleanFilter(); object lowerbound = value.Lower; object upperbound = value.Upper; const bool lowerboundincluded = true; const bool upperboundincluded = false; var currency = criteria.Currency.ToLower(); var upper = upperbound == null ? NumericUtils.LongToPrefixCoded(long.MaxValue) : ConvertToSearchable(upperbound); // format is "fieldname_store_currency_pricelist" string[] pls = null; var searchCriteria = criteria as CatalogItemSearchCriteria; if (searchCriteria != null) { pls = searchCriteria.Pricelists; } var parentPriceList = String.Empty; // Create filter of type // price_USD_pricelist1:[100 TO 200} (-price_USD_pricelist1:[* TO *} +(price_USD_pricelist2:[100 TO 200} (-price_USD_pricelist2:[* TO *} (+price_USD_pricelist3[100 TO 200})))) if (pls == null || !pls.Any()) { return null; } var priceListId = pls[0].ToLower(); var filter = new TermRangeFilter( String.Format("{0}_{1}_{2}", field, currency, priceListId), ConvertToSearchable(lowerbound), upper, lowerboundincluded, upperboundincluded); query.Add(new FilterClause(filter, Occur.SHOULD)); if (pls.Count() > 1) { var q = CreatePriceRangeQuery( pls, 1, field, currency, ConvertToSearchable(lowerbound), upper, lowerboundincluded, upperboundincluded); query.Add(new FilterClause(q, Occur.SHOULD)); } return query; }
public void StartSearching(ISearchCriteria criteria) { IRequest request = new Request(criteria, Callback); StartSearching(request); }
/// <summary> /// Builds the query. /// </summary> /// <param name="criteria">The criteria.</param> /// <returns></returns> public override object BuildQuery(ISearchCriteria criteria) { var builder = base.BuildQuery(criteria) as QueryBuilder; var query = builder.Query as BooleanQuery; var analyzer = new StandardAnalyzer(u.Version.LUCENE_30); if (criteria is CatalogItemSearchCriteria) { var c = criteria as CatalogItemSearchCriteria; var datesFilterStart = new TermRangeQuery( "startdate", c.StartDateFrom.HasValue ? DateTools.DateToString(c.StartDateFrom.Value, DateTools.Resolution.SECOND) : null, DateTools.DateToString(c.StartDate, DateTools.Resolution.SECOND), false, true); query.Add(datesFilterStart, Occur.MUST); if (c.EndDate.HasValue) { var datesFilterEnd = new TermRangeQuery( "enddate", DateTools.DateToString(c.EndDate.Value, DateTools.Resolution.SECOND), null, true, false); query.Add(datesFilterEnd, Occur.MUST); } if (c.Outlines != null && c.Outlines.Count > 0) { AddQuery("__outline", query, c.Outlines); } query.Add(new TermQuery(new Term("__hidden", "false")), Occur.MUST); if (!String.IsNullOrEmpty(c.Catalog)) { AddQuery("catalog", query, c.Catalog); } // Add search if (!String.IsNullOrEmpty(c.SearchPhrase)) { if (c.IsFuzzySearch) { var keywords = c.SearchPhrase.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); //var keywords = Regex.Split(c.SearchPhrase, @"\s+"); var searchPhrase = string.Empty; searchPhrase = keywords.Aggregate( searchPhrase, (current, keyword) => current + String.Format("{0}~{1}", keyword.Replace("~", ""), c.FuzzyMinSimilarity)); var parser = new QueryParser(u.Version.LUCENE_30, "__content", analyzer) { DefaultOperator = QueryParser .Operator.AND }; var searchQuery = parser.Parse(searchPhrase); query.Add(searchQuery, Occur.MUST); } else { var parser = new QueryParser(u.Version.LUCENE_30, "__content", analyzer) { DefaultOperator = QueryParser .Operator.AND }; var searchQuery = parser.Parse(c.SearchPhrase); query.Add(searchQuery, Occur.MUST); } } } else if (criteria is OrderSearchCriteria) { var c = criteria as OrderSearchCriteria; if (!String.IsNullOrEmpty(c.CustomerId)) { AddQuery("customerid", query, c.CustomerId); } } return builder; }
/// <summary> /// Calculates the result count. /// </summary> /// <param name="reader">The reader.</param> /// <param name="baseDocIdSet">The base doc id set.</param> /// <param name="facetGroup">The facet group.</param> /// <param name="filter">The filter.</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> private int CalculateResultCount(IndexReader reader, DocIdSet baseDocIdSet, FacetGroup facetGroup, ISearchFilter filter, ISearchCriteria criteria) { var count = 0; var values = LuceneQueryHelper.GetFilterValues(filter); if (values == null) { return 0; } BooleanFilter ffilter = null; foreach (var f in criteria.CurrentFilters) { if (!f.Key.Equals(facetGroup.FieldName)) { if (ffilter == null) ffilter = new BooleanFilter(); var q = LuceneQueryHelper.CreateQuery(criteria, f, Occur.SHOULD); ffilter.Add(new FilterClause(q, Occur.MUST)); } } foreach (var value in values) { var queryFilter = new BooleanFilter(); var valueFilter = LuceneQueryHelper.CreateQueryForValue(Results.SearchCriteria, filter, value); if (valueFilter == null) continue; queryFilter.Add(new FilterClause(valueFilter, Occur.MUST)); if(ffilter!=null) queryFilter.Add(new FilterClause(ffilter, Occur.MUST)); var filterArray = queryFilter.GetDocIdSet(reader); var newCount = (int)CalculateFacetCount(baseDocIdSet, filterArray); if (newCount == 0) continue; var newFacet = new Facet(facetGroup, value.Id, GetDescription(value, Results.SearchCriteria.Locale), newCount); facetGroup.Facets.Add(newFacet); count += newCount; } return count; }
/// <summary> /// Search users from repository according searchCriteria /// </summary> /// <param name="searchCriteria"> interface search criterias</param> public IEnumerable<int> SearchForUser(ISearchCriteria searchCriteria) { if (searchCriteria == null) throw new ArgumentNullException(); return searchCriteria.Search(_users); }
/// <summary> /// Creates the suggestions. /// </summary> /// <param name="reader">The reader.</param> /// <param name="criteria">The criteria.</param> private void CreateSuggestions(IndexReader reader, ISearchCriteria criteria) { if (criteria is KeywordSearchCriteria) { var c = criteria as KeywordSearchCriteria; var phrase = c.SearchPhrase; if (!String.IsNullOrEmpty(phrase)) { Results.Suggestions = SuggestSimilar(reader, "_content", phrase); } } }
public IEnumerable<InvoiceDisplay> SearchInvoices(ISearchCriteria criteria) { return InvoiceQuery.Search(criteria); }