Example #1
0
        public static FilterContainer GenerateBoolFilter <T>(this Expression expression) where T : class
        {
            var filterDescriptor = new FilterDescriptor <T>();
            var fieldName        = GenerateFilterName(expression);

            return(filterDescriptor.Term(fieldName, true));
        }
Example #2
0
        public static FilterContainer GenerateEqualityFilter <T>(this Expression expression) where T : class
        {
            var binaryExpression = expression as BinaryExpression;
            var value            = GetValue(binaryExpression.Right);

            if (FSharpType.IsUnion(value.GetType(), FSharpOption <BindingFlags> .None))
            {
                var fields    = FSharpValue.GetUnionFields(value, value.GetType(), FSharpOption <BindingFlags> .None);
                var unionCase = fields.Item1;
                value = unionCase.Name;
            }
            var filterDescriptor = new FilterDescriptor <T>();
            var fieldName        = GetFieldName(binaryExpression.Left);

            return(filterDescriptor.Term(fieldName, value));
        }
        /// <summary>
        /// Querying combining fields
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
        public List <DTO.Customer> QueryUsingCombinations(DTO.CombinedFilter filter)
        {
            //Build Elastic "Should" filtering object for "Ages":
            FilterContainer[] agesFiltering = new FilterContainer[filter.Ages.Count];
            for (int i = 0; i < filter.Ages.Count; i++)
            {
                FilterDescriptor <DTO.Customer> clause = new FilterDescriptor <DTO.Customer>();
                agesFiltering[i] = clause.Term("age", int.Parse(filter.Ages[i]));
            }

            //Build Elastic "Must Not" filtering object for "Names":
            FilterContainer[] nameFiltering = new FilterContainer[filter.Names.Count];
            for (int i = 0; i < filter.Names.Count; i++)
            {
                FilterDescriptor <DTO.Customer> clause = new FilterDescriptor <DTO.Customer>();
                nameFiltering[i] = clause.Term("name", filter.Names[i]);
            }

            //Run the combined query:
            var hits = _EsClientDAL.Current.Search <DTO.Customer>(s => s
                                                                  .Query(q => q
                                                                         .Filtered(fq => fq
                                                                                   .Query(qq => qq.MatchAll())
                                                                                   .Filter(ff => ff
                                                                                           .Bool(b => b
                                                                                                 .Must(m1 => m1.Term("hasChildren", filter.HasChildren))
                                                                                                 .MustNot(nameFiltering)
                                                                                                 .Should(agesFiltering)
                                                                                                 )
                                                                                           )
                                                                                   )
                                                                         )
                                                                  ).Hits;

            //Translate the hits and return the list
            List <DTO.Customer> typedList = hits.Select(hit => ConvertHitToCustumer(hit)).ToList();

            return(typedList);
        }
Example #4
0
        protected void parseExpression(Expression expressionTree)
        {
            if (expressionTree == null)
            {
                return;
            }

            if (expressionTree is BinaryExpression && expressionTree.NodeType == ExpressionType.AndAlso &&
                ((BinaryExpression)expressionTree).Left != null)
            {
                parseExpression(((BinaryExpression)expressionTree).Left);
            }

            if (expressionTree is BinaryExpression && expressionTree.NodeType == ExpressionType.AndAlso &&
                ((BinaryExpression)expressionTree).Right != null)
            {
                parseExpression(((BinaryExpression)expressionTree).Right);
            }

            if (expressionTree.NodeType == ExpressionType.Equal || expressionTree.NodeType == ExpressionType.NotEqual)
            {
                BinaryExpression binaryExpression = expressionTree as BinaryExpression;

                string parameterName = "";
                if (binaryExpression.Left.GetType().Equals(typeof(UnaryExpression)))
                {
                    UnaryExpression  unaryExpression = binaryExpression.Left as UnaryExpression;
                    MemberExpression left            = unaryExpression.Operand as MemberExpression;
                    parameterName = left.Member.Name;
                }
                else
                {
                    MemberExpression left = binaryExpression.Left as MemberExpression;
                    parameterName = left.Member.Name;
                }

                string parameterValue = "";
                if (binaryExpression.Right.NodeType == ExpressionType.Convert)
                {
                    UnaryExpression    right              = binaryExpression.Right as UnaryExpression;
                    MemberExpression   memberExpression   = right.Operand as MemberExpression;
                    ConstantExpression constantExpression = memberExpression.Expression as ConstantExpression;
                    object             container          = constantExpression.Value;
                    var member = memberExpression.Member;
                    if (member is FieldInfo)
                    {
                        FieldInfo fieldInfo = member as FieldInfo;
                        if (fieldInfo.FieldType.IsEnum)
                        {
                            object value = ((FieldInfo)member).GetValue(container);
                            //var en = Enum.ToObject(fieldInfo.FieldType, value);
                            var enumValue = (short)value;
                            parameterValue = enumValue.ToString();
                        }
                        else
                        {
                            object value = ((FieldInfo)member).GetValue(container);
                            parameterValue = value.ToString();
                        }
                    }
                    if (member is PropertyInfo)
                    {
                        //object value = ((PropertyInfo)member).GetValue(container, null);
                    }
                }
                else if (binaryExpression.Right.NodeType != ExpressionType.Constant)
                {
                    MemberExpression memberExpression = binaryExpression.Right as MemberExpression;
                    // MemberExpression fieldExpression = memberExpression.Expression as MemberExpression;
                    ConstantExpression right = memberExpression.Expression as ConstantExpression;
                    //parameterValue = right.Value.ToString();

                    object container = right.Value;
                    var    member    = memberExpression.Member;
                    if (member is FieldInfo)
                    {
                        object value = ((FieldInfo)member).GetValue(container);
                        parameterValue = value.ToString();
                    }
                    if (member is PropertyInfo)
                    {
                        //object value = ((PropertyInfo)member).GetValue(container, null);
                    }
                }
                else
                {
                    ConstantExpression right = binaryExpression.Right as ConstantExpression;
                    parameterValue = right.Value.ToString();
                }
                if (expressionTree.NodeType == ExpressionType.Equal)
                {
                    FilterDescriptor <T> filterD = new FilterDescriptor <T>();
                    FilterContainer      filter  = filterD.Term(parameterName.ToCamelCase(), parameterValue);
                    stack.Push(filter);
                }
                else
                {
                    FilterDescriptor <T> filterD = new FilterDescriptor <T>();
                    FilterContainer      filter  = filterD.Not(n => n.Term(parameterName.ToCamelCase(), parameterValue));
                    stack.Push(filter);
                }
            }
            else if (expressionTree.NodeType == ExpressionType.Lambda)
            {
                LambdaExpression     lambdaExpression     = expressionTree as LambdaExpression;
                MethodCallExpression methodCallExpression = lambdaExpression.Body as MethodCallExpression;
                MemberExpression     memberExpression     = methodCallExpression.Object as MemberExpression;
                if (memberExpression.NodeType == ExpressionType.MemberAccess)
                {
                    memberExpression = memberExpression.Expression as MemberExpression;
                }

                ConstantExpression constantExpression = methodCallExpression.Arguments[0] as ConstantExpression;

                string parameterName  = memberExpression.Member.Name;
                string parameterValue = constantExpression.Value.ToString();

                FilterDescriptor <T> filterD    = new FilterDescriptor <T>();
                FilterContainer      baseFilter = filterD.Term(parameterName.ToCamelCase(), parameterValue);

                stack.Push(baseFilter);
            }
            else if (expressionTree.NodeType == ExpressionType.Call)
            {
                MethodCallExpression methodCallExpression = expressionTree as MethodCallExpression;
                Expression           collectionExpression = null;
                MemberExpression     memberExpression     = null;
                if (methodCallExpression != null && methodCallExpression.Method.Name == "Contains")
                {
                    if (methodCallExpression.Method.DeclaringType == typeof(Enumerable))
                    {
                        collectionExpression = methodCallExpression.Arguments[0];
                        memberExpression     = methodCallExpression.Arguments[1] as MemberExpression;
                    }
                    else
                    {
                        collectionExpression = methodCallExpression.Object;
                        memberExpression     = methodCallExpression.Arguments[0] as MemberExpression;
                    }

                    string parameterValue = string.Empty;
                    var    paramvalue     = new List <int>();
                    if (collectionExpression != null && memberExpression != null)
                    {
                        var lambda = Expression.Lambda <Func <List <int> > >(collectionExpression, new ParameterExpression[0]);
                        var value  = lambda.Compile()();
                        parameterValue = memberExpression.Member.Name.ToCamelCase();
                        paramvalue     = value;
                    }
                    FilterDescriptor <T> filterD = new FilterDescriptor <T>();
                    //FilterContainer baseFilter = filterD.Term(memberExpression.Member.Name.ToCamelCase(), paramvalue);
                    FilterContainer baseFilter = filterD.Terms(parameterValue, paramvalue.Select(i => i.ToString()).ToList());

                    stack.Push(baseFilter);
                }
                else
                {
                    memberExpression = methodCallExpression.Object as MemberExpression;
                    if (memberExpression.NodeType == ExpressionType.MemberAccess)
                    {
                        memberExpression = memberExpression.Expression as MemberExpression;
                    }

                    ConstantExpression constantExpression = methodCallExpression.Arguments[0] as ConstantExpression;

                    string parameterName  = memberExpression.Member.Name;
                    string parameterValue = constantExpression.Value.ToString();

                    FilterDescriptor <T> filterD    = new FilterDescriptor <T>();
                    FilterContainer      baseFilter = filterD.Term(parameterName.ToCamelCase(), parameterValue);
                    stack.Push(baseFilter);
                }
            }
            else if (expressionTree.NodeType == ExpressionType.AndAlso)
            {
                //BinaryExpression binaryExpression = expressionTree as BinaryExpression;
                IList <FilterContainer> filters = new List <FilterContainer>();

                foreach (var i in Enumerable.Range(1, stack.Count))
                {
                    FilterContainer filter = stack.Pop();
                    filters.Add(filter);
                }

                FilterDescriptor <T> filterD    = new FilterDescriptor <T>();
                FilterContainer      baseFilter = filterD.And(filters.ToArray());
                stack.Push(baseFilter);
            }
        }
Example #5
0
        SearchResult <T> search <D>(string q, Expression <Func <T, bool> > filter, SearchParameters searchParameters)
        {
            SearchResult <T> searchResult = new SearchResult <T>();
            int limit = searchParameters.Limit == 0 ? 10 : searchParameters.Limit;
            int from  = (searchParameters.PageNumber - 1) * limit;
            ISearchResponse <T> result;
            //string[] types = searchParameters.Types.Select(t => t.FullName).ToArray();

            SearchDescriptor <T> descriptor = new SearchDescriptor <T>();

            descriptor = descriptor.Types(searchParameters.Types)
                         .From(from)
                         .Size(limit);
            descriptor = descriptor.Filter(f => f.Term("accountID", searchParameters.AccountId));

            if (typeof(T).Equals(typeof(Campaign)))
            {
                if (searchParameters.SortField == ContactSortFieldType.CampaignClickrate)
                {
                    descriptor = descriptor.Sort(s => s.OnField("uniqueClicks").Descending().UnmappedType(Nest.FieldType.None));
                }
                else if (!searchParameters.SortFields.IsAny())
                {
                    descriptor = descriptor.Sort(s => s.OnField("lastUpdatedOn").Descending().UnmappedType(Nest.FieldType.None));
                }
            }
            else if (typeof(T).Equals(typeof(Form)) && !searchParameters.SortFields.IsAny())
            {
                descriptor = descriptor.Sort(s => s.OnField("lastModifiedOn").Descending().UnmappedType(Nest.FieldType.None));
            }
            else if (typeof(T).Equals(typeof(Opportunity)) && !searchParameters.SortFields.IsAny())
            {
                descriptor = descriptor.Sort(s => s.OnField("createdOn").Descending().UnmappedType(Nest.FieldType.None));
            }

            if (searchParameters != null && searchParameters.SortFields.IsAny())
            {
                //todo multi-level sorting.
                string sortField = searchParameters.SortFields.First();
                if (searchParameters.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
                {
                    descriptor = descriptor.Sort(s => s.OnField(sortField.ToCamelCase()).Ascending().UnmappedType(Nest.FieldType.None));
                }
                else
                {
                    descriptor = descriptor.Sort(s => s.OnField(sortField.ToCamelCase()).Descending().UnmappedType(Nest.FieldType.None));
                }
            }

            if (!string.IsNullOrEmpty(q))
            {
                descriptor = descriptor.Query(query => query.QueryString(qs => qs.Query(q)));
            }

            if (filter != null)
            {
                string createddate = typeof(T).Equals(typeof(Form)) ? "createdDate" : (typeof(T).Equals(typeof(Campaign)) ? "createdDate" : "createdOn");
                Expression <Func <T, bool> > expression = filter;
                parseExpression(expression.Body);
                FilterContainer      baseFilter         = stack.Pop();
                FilterDescriptor <T> filterD            = new FilterDescriptor <T>();
                FilterContainer      accountIDFilter    = filterD.Term("accountID", searchParameters.AccountId);
                FilterContainer      dateRangeContainer = new FilterContainer();
                if (searchParameters.StartDate.HasValue && searchParameters.EndDate.HasValue)
                {
                    FilterDescriptor <T> dateRangeFilter = new FilterDescriptor <T>();
                    dateRangeContainer = dateRangeFilter.Range(r =>
                                                               r.GreaterOrEquals(searchParameters.StartDate.Value.ToJSDate()).
                                                               LowerOrEquals(searchParameters.EndDate.Value.ToJSDate()).OnField(createddate));
                }
                descriptor = descriptor.Filter(f => f.And(baseFilter, accountIDFilter, dateRangeContainer));
            }

            if (searchParameters != null && searchParameters.Ids.IsAny())
            {
                if (!string.IsNullOrEmpty(q))
                {
                    descriptor = descriptor.Filter(ds => ds.Terms("id", searchParameters.Ids, TermsExecution.Plain));
                }
                else
                {
                    descriptor = descriptor.Query(query => query.Ids(searchParameters.Ids.Select(i => i.ToString()).ToList()));
                }
            }



            result = ElasticClient().Search <T>(body => descriptor);
            string que = result.ConnectionStatus.ToString();

            Logger.Current.Verbose(que);

            searchResult.Results   = result.Documents;
            searchResult.TotalHits = result.Total;

            return(searchResult);
        }
Example #6
0
        public SearchResult <Suggestion> QuickSearch(string q, SearchParameters parameters)
        {
            int limit = parameters.Limit == 0 ? 10 : parameters.Limit;
            int from  = (parameters.PageNumber - 1) * limit;

            SearchDescriptor <object> descriptor = new SearchDescriptor <object>();

            descriptor = descriptor.From(from).Size(limit);

            IList <FilterContainer> filters = new List <FilterContainer>();

            FilterDescriptor <object> baseFilter = new FilterDescriptor <object>();

            filters.Add(baseFilter.Term("accountID", parameters.AccountId));
            if (parameters != null && parameters.IsPrivateSearch && parameters.PrivateModules.IsAny() &&
                (parameters.PrivateModules.Contains(Entities.AppModules.Campaigns) || parameters.PrivateModules.Contains(Entities.AppModules.Forms)))
            {
                filters.Add(baseFilter.Term("ownerId", parameters.DocumentOwnerId.ToString()));
                //if(parameters.PrivateModules.Count() > 0 &&
                //parameters.PrivateModules.Contains(Entities.AppModules.Campaigns) )
                //    filters.Add(baseFilter.Term("status", 109));
            }

            if (filters.Count > 1)
            {
                descriptor = descriptor.Filter(f => f.And(filters.ToArray()));
            }
            else
            {
                descriptor = descriptor.Filter(f => f.Term("accountID", parameters.AccountId));
            }
            //descriptor = descriptor.Filter(f => f.Term("accountID", parameters.AccountId));

            string[] selectedIndices = null;
            Type[]   types           = null;

            if (parameters != null && parameters.Types.IsAny())
            {
                selectedIndices = parameters.Types.Where(t => indices.ContainsKey(t)).Select(t => indices[t]).Distinct().ToArray();
                types           = parameters.Types.Distinct().ToArray();
            }
            else
            {
                selectedIndices = indices.Select(c => c.Value).Distinct().ToArray();
                types           = indices.Select(c => c.Key).Distinct().ToArray();
            }

            descriptor = descriptor.Indices(selectedIndices).IndicesBoost(b => b
                                                                          .Add("contacts" + this.accountId, 3.5).Add("campaigns" + this.accountId, 3.0).Add("opportunities", 2.5));

            descriptor = descriptor.Types(types);
            if (!string.IsNullOrEmpty(q))
            {
                string queryString = q + "*" + " " + q;
                if (parameters != null && parameters.PrivateModules.IsAny())
                {
                    string createdByTerm      = string.Empty;
                    string createdByTermValue = string.Empty;
                    string ownerIdTerm        = string.Empty;
                    string ownerIdTermValue   = string.Empty;
                    if (parameters.PrivateModules.Contains(Entities.AppModules.Campaigns) || parameters.PrivateModules.Contains(Entities.AppModules.Forms))
                    {
                        createdByTerm      = "createdBy";
                        createdByTermValue = parameters.DocumentOwnerId.ToString();
                    }


                    if (parameters.PrivateModules.Contains(Entities.AppModules.Contacts) || parameters.PrivateModules.Contains(Entities.AppModules.Opportunity))
                    {
                        ownerIdTerm      = "ownerId";
                        ownerIdTermValue = parameters.DocumentOwnerId.ToString();
                    }

                    IList <string> contactIndices = new List <string>();
                    if (parameters.PrivateModules.Contains(Entities.AppModules.Contacts))
                    {
                        contactIndices.Add("contacts" + this.accountId);
                    }
                    //if (parameters.PrivateModules.Contains(Entities.AppModules.Opportunity))  commented by Ram on 2nd May 2018 CR NEXG-3001
                    //    contactIndices.Add("opportunities");  commented by Ram on 2nd May 2018 CR NEXG-3001
                    //if (parameters.PrivateModules.Contains(Entities.AppModules.Campaigns)) commented by Ram on 2nd May 2018 CR NEXG-3001
                    //    contactIndices.Add("campaigns" + this.accountId);  commented by Ram on 2nd May 2018 CR NEXG-3001
                    if (parameters.PrivateModules.Contains(Entities.AppModules.Forms))
                    {
                        contactIndices.Add("forms");
                    }

                    //descriptor = descriptor.Query(qr=>qr.Filtered(flt=>flt.Query(qs=>qs.in)))
                    // descriptor = descriptor.Query(qu => qu.Indices(i => i.Indices(contactIndices)
                    //.NoMatchQuery(nm => nm.Term(createdByTerm, createdByTermValue)).NoMatchQuery(nm => nm.Term(ownerIdTerm, ownerIdTermValue)).Query(qr => qr.QueryString(qs => qs.Query(q)))));//Term(ownerIdTerm, ownerIdTermValue)

                    //modified

                    descriptor = descriptor.Query(qu =>
                                                  qu.Indices(i => i.Indices(contactIndices).
                                                             NoMatchQuery(nm => nm.QueryString(qs => qs.Query(queryString))).
                                                             Query(que => que.Bool(b => b.Must(
                                                                                       s => s.Bool(bo => bo.Should(sh => sh.Term(createdByTerm, createdByTermValue), sh => sh.Term(ownerIdTerm, ownerIdTermValue))),
                                                                                       s => s.QueryString(qs => qs.Query(queryString).OnFieldsWithBoost(o => o.Add("firstName", 5).Add("lastName", 5).Add("emails.emailId", 5).Add("companyName", 3.5).Add("_all", 2))))))));
                }
                else
                {
                    descriptor = descriptor.Query(query => query.QueryString(qs => qs.Query(queryString).OnFieldsWithBoost(o => o.Add("firstName", 5).Add("lastName", 5).Add("emails.emailId", 5).Add("companyName", 3.5).Add("_all", 2))));
                }
            }

            /*
             * Don't show archived campaigns, search by account id, don't show unsubscribed email
             * */
            descriptor = descriptor.Filter(f => f.And(query => !query.Term("campaignStatus", CampaignStatus.Archive),
                                                      query => query.Term("accountID", parameters.AccountId)));
            var result = this.ElasticClient().Search <object>(body => descriptor);

            string qe = result.ConnectionStatus.ToString();

            Logger.Current.Verbose(qe);

            var searchResult = convertToSuggestions(result.Documents, parameters);

            searchResult.TotalHits = result.Total;

            return(searchResult);
        }