Example #1
0
        public async Task <ActionResult> Submit(string type, string query)
        {
            if (!string.IsNullOrWhiteSpace(query) && type == "1")
            {
                var model = new SearchFormModel
                {
                    SearchResult = await _movieRepository.SearchByTitle(query).ConfigureAwait(false)
                };

                return(PartialView("_MovieSearchResult", model));
            }

            var hitSpec = new HitSpecification
            {
                ExcerptLength = 255
            };

            var findModel = new FindResultViewModel
            {
                Result = SearchClient.Instance.UnifiedSearchFor(query)
                         .UsingSynonyms()
                         .ApplyBestBets()
                         .Take(100)
                         .GetResult(hitSpec)
            };

            return(PartialView("_FindSearchResult", findModel));
        }
Example #2
0
        public ViewResult Index(FindPage currentPage, string q)
        {
            var model = new FindSearchContentModel(currentPage)
            {
                PublicProxyPath = _findUIConfiguration.AbsolutePublicProxyPath()
            };

            if (!string.IsNullOrWhiteSpace(model.Query))
            {
                var query =
                    _searchClient.UnifiedSearchFor(model.Query, _searchClient.Settings.Languages.GetSupportedLanguage(ContentLanguage.PreferredCulture) ??
                                                   Language.None)
                    .UsingSynonyms()
                    //Include a facet whose value we can use to show the total number of hits
                    //regardless of section. The filter here is irrelevant but should match *everything*.
                    .TermsFacetFor(x => x.SearchSection)
                    .FilterFacet("AllSections", x => x.SearchSection.Exists())
                    //Fetch the specific paging page.
                    .Skip((model.PagingPage - 1) * model.CurrentPage.PageSize)
                    .Take(model.CurrentPage.PageSize)
                    //Range facet for date
                    //.RangeFacetFor(x => x.SearchUpdateDate, model.PublishedDateRange.ToArray())
                    //Allow editors (from the Find/Optimizations view) to push specific hits to the top
                    //for certain search phrases.
                    .ApplyBestBets();

                // obey DNT
                var doNotTrackHeader = System.Web.HttpContext.Current.Request.Headers.Get("DNT");
                // Should Not track when value equals 1
                if (doNotTrackHeader == null || doNotTrackHeader.Equals("0"))
                {
                    query = query.Track();
                }

                //If a section filter exists (in the query string) we apply
                //a filter to only show hits from a given section.
                if (!string.IsNullOrWhiteSpace(model.SectionFilter))
                {
                    query = query.FilterHits(x => x.SearchSection.Match(model.SectionFilter));
                }

                //We can (optionally) supply a hit specification as argument to the GetResult
                //method to control what each hit should contain. Here we create a
                //hit specification based on values entered by an editor on the search page.
                var hitSpec = new HitSpecification
                {
                    HighlightTitle   = model.CurrentPage.HighlightTitles,
                    HighlightExcerpt = model.CurrentPage.HighlightExcerpts
                };

                //Execute the query and populate the Result property which the markup (aspx)
                //will render.
                model.Hits = query.GetResult(hitSpec);
            }

            return(View(model));
        }
Example #3
0
        public IHttpActionResult Search(string query)
        {
            var hitSpecification = new HitSpecification();

            var result = _client.UnifiedSearchFor(query)
                         .StatisticsTrack()
                         .GetResult();

            return(Json(result));
        }
Example #4
0
        public ContentSearchViewModel SearchContent(FilterOptionViewModel filterOptions)
        {
            var model = new ContentSearchViewModel
            {
                FilterOption = filterOptions
            };

            if (!filterOptions.Q.IsNullOrEmpty())
            {
                var siteId = SiteDefinition.Current.Id;
                var query  = _findClient.UnifiedSearchFor(filterOptions.Q, _findClient.Settings.Languages.GetSupportedLanguage(ContentLanguage.PreferredCulture) ?? Language.None)
                             .UsingSynonyms()
                             .TermsFacetFor(x => x.SearchSection)
                             .FilterFacet("AllSections", x => x.SearchSection.Exists())
                             .Filter(x => (x.MatchTypeHierarchy(typeof(FoundationPageData)) & (((FoundationPageData)x).SiteId().Match(siteId.ToString())) | (x.MatchTypeHierarchy(typeof(PageData)) & x.MatchTypeHierarchy(typeof(MediaData)))))
                             .Skip((filterOptions.Page - 1) * filterOptions.PageSize)
                             .Take(filterOptions.PageSize)
                             .ApplyBestBets();

                //Include images in search results
                if (!filterOptions.IncludeImagesContent)
                {
                    query = query.Filter(x => !x.MatchType(typeof(ImageMediaData)));
                }

                //Exclude content from search
                query = query.Filter(x => !(x as FoundationPageData).ExcludeFromSearch.Exists() | (x as FoundationPageData).ExcludeFromSearch.Match(false));

                // obey DNT
                var doNotTrackHeader = System.Web.HttpContext.Current.Request.Headers.Get("DNT");
                if ((doNotTrackHeader == null || doNotTrackHeader.Equals("0")) && filterOptions.TrackData)
                {
                    query = query.Track();
                }

                if (!string.IsNullOrWhiteSpace(filterOptions.SectionFilter))
                {
                    query = query.FilterHits(x => x.SearchSection.Match(filterOptions.SectionFilter));
                }

                var hitSpec = new HitSpecification
                {
                    HighlightTitle   = true,
                    HighlightExcerpt = true
                };

                model.Hits = query.GetResult(hitSpec);
                filterOptions.TotalCount = model.Hits.TotalMatching;
            }

            return(model);
        }
        /// <summary>
        /// When the page is loaded a search is carried out based on the 'q' query string parameter
        /// </summary>
        protected override void OnLoad(EventArgs eventArgs)
        {
            PublicProxyPath = ServiceLocator.Current.GetInstance <IFindUIConfiguration>().AbsolutePublicProxyPath();

            //detect if serviceUrl and/or defaultIndex is configured.
            IsConfigured = SearchIndexIsConfigured(EPiServer.Find.Configuration.GetConfiguration());

            if (IsPostBack)
            {
                Query      = srchTxt.Text;
                PagingPage = 1;
            }
            else
            {
                Query        = Request.Params["q"];
                srchTxt.Text = Query;
                PagingPage   = Request.Params["p"].IsNotNullOrEmpty() ? int.Parse(Request.Params["p"]) : 1;
            }

            if (IsConfigured && !string.IsNullOrWhiteSpace(Query))
            {
                var query = BuildQuery();

                //Create a hit specification to determine display based on values entered by an editor on the search page.
                var hitSpec = new HitSpecification
                {
                    HighlightTitle   = CurrentPage.HighlightTitles,
                    HighlightExcerpt = CurrentPage.HighlightExcerpts,
                    ExcerptLength    = CurrentPage.ExcerptLength
                };

                try
                {
                    Hits = query.GetResult(hitSpec);
                }
                catch (WebException wex)
                {
                    IsConfigured = wex.Status != WebExceptionStatus.NameResolutionFailure;
                }

                DisplaySearchResult();
            }

            // Databind for translations
            SearchButton.DataBind();

            RequireClientResources();
        }
Example #6
0
        /// <summary>
        /// Catches <see cref="ServiceException"/> and <see cref="ClientException"/> and returns an <see cref="EmptyUnifiedSearchResults"/>
        /// </summary>
        public static UnifiedSearchResults GetResultSafe(
            this ITypeSearch <ISearchContent> search,
            HitSpecification hitSpecification = null,
            bool filterForPublicSearch        = true)
        {
            UnifiedSearchResults contentResult = null;

            try
            {
                contentResult =
                    search.GetResult(hitSpecification, filterForPublicSearch);
            }
            catch (Exception ex) when(ex is ClientException || ex is ServiceException)
            {
                Log.Error("Could not retrieve data from find, returning empty UnifiedSearchResults", ex);
                contentResult = new EmptyUnifiedSearchResults();
            }
            return(contentResult);
        }
        public ViewResult Index(FindSearchPage currentPage, string q, string selectedAnalyzer)
        {
            var model = new FindSearchContentModel(currentPage)
            {
                PublicProxyPath = findUIConfiguration.AbsolutePublicProxyPath()
            };

            var parameters = Request.Url != null ? Request.Url.Query : string.Empty;

            model.OtherLanguageUrl = model.OtherLanguageUrl + parameters;

            //detect if serviceUrl and/or defaultIndex is configured.
            model.IsConfigured = SearchIndexIsConfigured(EPiServer.Find.Configuration.GetConfiguration());

            if (model.IsConfigured && !string.IsNullOrWhiteSpace(model.Query))
            {
                var query = BuildQuery(model, selectedAnalyzer);

                //Create a hit specification to determine display based on values entered by an editor on the search page.
                var hitSpec = new HitSpecification
                {
                    HighlightTitle   = model.CurrentPage.HighlightTitles,
                    HighlightExcerpt = model.CurrentPage.HighlightExcerpts,
                    // When HighlightExcerpt = true then minimum of ExcerptLength = 36
                    ExcerptLength = model.CurrentPage.HighlightExcerpts && model.ExcerptLength < 36 ? 36 : model.ExcerptLength
                };

                try
                {
                    model.Hits = query.GetResult(hitSpec);
                }
                catch (WebException wex)
                {
                    model.IsConfigured = wex.Status != WebExceptionStatus.NameResolutionFailure;
                }
            }

            model.Analyzers = CreateAnalyzers(selectedAnalyzer);

            RequireClientResources();

            return(View(model));
        }
Example #8
0
        public IHttpActionResult HighlightUnifiedSearch(
            string query,
            int numberOfFragments,
            int fragmentSize,
            string preTag,
            string postTag,
            string concatentation)
        {
            var hitSpecification = new HitSpecification();

            hitSpecification.HighlightExcerpt = true;
            hitSpecification.HighlightTitle   = true;
            if (!string.IsNullOrEmpty(preTag))
            {
                hitSpecification.PreTagForAllHighlights = preTag;
            }
            if (!string.IsNullOrEmpty(postTag))
            {
                hitSpecification.PostTagForAllHighlights = postTag;
            }
            hitSpecification.ExcerptHighlightSpecAction = x =>
            {
                if (fragmentSize > 0)
                {
                    x.FragmentSize = fragmentSize;
                }
                if (numberOfFragments > 0)
                {
                    x.NumberOfFragments = numberOfFragments;
                }
                if (!string.IsNullOrEmpty(concatentation))
                {
                    x.Concatenation = (IEnumerable <string> strings) => string.Join(concatentation, strings);
                }
            };

            var result = _client.UnifiedSearchFor(query)
                         .GetResult(hitSpecification);

            return(Json(result));
        }
        public ViewResult Index(FindSearchPage currentPage, string q)
        {
            var model = new FindSearchContentModel(currentPage)
            {
                PublicProxyPath = findUIConfiguration.AbsolutePublicProxyPath()
            };

            //detect if serviceUrl and/or defaultIndex is configured.

            var findConfiguration = EPiServer.Find.Configuration.GetConfiguration();

            model.IsConfigured = !findConfiguration.ServiceUrl.IsNullOrEmpty() &&
                                 !findConfiguration.DefaultIndex.IsNullOrEmpty();

            if (model.IsConfigured && !string.IsNullOrWhiteSpace(model.Query))
            {
                var query = BuildQuery(model);

                //Create a hit specification to determine display based on values entered by an editor on the search page.
                var hitSpec = new HitSpecification
                {
                    HighlightTitle   = model.CurrentPage.HighlightTitles,
                    HighlightExcerpt = model.CurrentPage.HighlightExcerpts,
                    ExcerptLength    = model.ExcerptLength
                };

                try
                {
                    model.Hits = query.GetResult(hitSpec);
                }
                catch (WebException wex)
                {
                    model.IsConfigured = wex.Status != WebExceptionStatus.NameResolutionFailure;
                }
            }

            RequireClientResources();

            return(View(model));
        }
Example #10
0
        public FindResponse Find([FromBody] QueryObject query)
        {
            //^[a-zA-ZåäöÅÄÖ\s]+\s(\d+|\*)\:\s?\d+$   gävle torp 7:3
            //^[a-zA-ZåäöÅÄÖ(\s|\+)]+(\s|\+)(\d+|\*)\:(\s|\+)?\d+$    gävle+torp+7:3
            if (Regex.Match(query.Text, @"^[a-zA-ZåäöÅÄÖ(\s|\+)]+(\s|\+)(\d+|\*)\:(\s|\+)?\d+$").Success)
            {
                query.Text = "fastighetsbeteckning";
            }
            var client = SearchClient.Instance;

            searchroot = query.SearchRoot;
            client.Conventions.ForInstancesOf <object>().FieldsOfType <string>().StripHtml();

            Language l = Language.Swedish;

            if (query.SearchLanguage != null && query.SearchLanguage == "en")
            {
                l = Language.English;
            }

            var search = client.UnifiedSearchFor(query.Text, l)
                         .UsingSynonyms().WithAndAsDefaultOperator()
                         .TermsFacetFor(x => x.SearchTitle)
                         .Track();

            //ta bara från sökrot men inkludera alla Mediadata
            search = search.Filter(p => (p as IContent).Ancestors().Match(query.SearchRoot.ToString())).OrFilter(x => x.MatchTypeHierarchy(typeof(MediaData)));

            if (!query.IncludeMediafiles)
            {
                search = search.Filter(x => !x.MatchTypeHierarchy(typeof(MediaData)));
            }
            if (!query.IncludeConnectors)
            {
                search = search.Filter(x => !x.MatchTypeHierarchy(typeof(WebContent)));
            }

            var docResult  = search.Filter(x => x.MatchTypeHierarchy(typeof(MediaData))).ApplyBestBets().GetResult();
            var pageResult = search.Filter(x => x.MatchTypeHierarchy(typeof(PageData))).ApplyBestBets().GetResult();

            if (query.Type == "page")
            {
                search = search.Filter(x => x.MatchTypeHierarchy(typeof(PageData)));
            }

            if (query.Type == "doc")
            {
                search = search.Filter(x => x.MatchTypeHierarchy(typeof(MediaData)));
            }

            var hitSpecification = new HitSpecification {
                HighlightExcerpt = true, HighlightTitle = true
            };
            var result = search.Skip(query.Skip).Take(query.Take).ApplyBestBets().GetResult(hitSpecification);

            var output       = result.Select(GetCommonSearchHit);
            var findresponse = new FindResponse
            {
                Created   = DateTime.Now,
                Hits      = output.ToList(),
                Total     = result.TotalMatching,
                PageTotal = pageResult.TotalMatching,
                DocTotal  = docResult.TotalMatching,
                Success   = true,
                Tab       = query.Type
            };

            return(findresponse);
        }
Example #11
0
        private static Expression <Func <ISearchContent, string> > HighlightExpressionGetter(HitSpecification spec)
        {
            var highlightSpec = new HighlightSpec
            {
                FragmentSize      = spec.ExcerptLength,
                NumberOfFragments = 1,
                PreTag            = spec.PreTagForAllHighlights,
                PostTag           = spec.PostTagForAllHighlights
            };

            return(doc => !string.IsNullOrWhiteSpace(doc.SearchAttachmentText) ?
                   doc.SearchAttachmentText.AsHighlighted(highlightSpec) : doc.SearchAttachment.AsHighlighted(highlightSpec));
        }
        public IHttpActionResult Search(string query)
        {
            var hitSpecification = new HitSpecification();

            var result = _client.UnifiedSearchFor(query)
                .StatisticsTrack()
                .GetResult();

            return Json(result);
        }
        public IHttpActionResult HighlightUnifiedSearch(
            string query,
            int numberOfFragments,
            int fragmentSize,
            string preTag,
            string postTag, 
            string concatentation)
        {
            var hitSpecification = new HitSpecification();
            hitSpecification.HighlightExcerpt = true;
            hitSpecification.HighlightTitle = true;
            if (!string.IsNullOrEmpty(preTag))
            {
                hitSpecification.PreTagForAllHighlights = preTag;
            }
            if (!string.IsNullOrEmpty(postTag))
            {
                hitSpecification.PostTagForAllHighlights = postTag;
            }
            hitSpecification.ExcerptHighlightSpecAction = x =>
            {
                if (fragmentSize > 0)
                {
                    x.FragmentSize = fragmentSize;
                }
                if (numberOfFragments > 0)
                {
                    x.NumberOfFragments = numberOfFragments;
                }
                if (!string.IsNullOrEmpty(concatentation))
                {
                    x.Concatenation = (IEnumerable<string> strings) => string.Join(concatentation, strings);
                }
            };

            var result = _client.UnifiedSearchFor(query)
                .GetResult(hitSpecification);

            return Json(result);
        }