Wednesday, November 27, 2019

MVP Application

2020



Objectives: As a technology MVP in 2020 I plan to be influential in transitioning to a new Sitecore SaaS and headless architecture among my current and prospective clients. I believe the SaaS offering will reinvent the entire Sitecore experience.



Why eligible: I am currently a Sitecore MVP (Technology) and would like to maintain my MVP status. As a Sitecore Architect with a partner agency XCentium I not only implement sitecore solutions but evangelize and outreach to potential clients who might be interested in using Sitecore. I am so active in Women of Sitecore community where we strive to support and encourage other women to join the world of technology without fear and doubt instilled in them by cultural stereotypes they grew up with.



Summary of relevant online professional activity: I blog about my work and I put particular emphasis on struggles and discoveries that we Sitecore engineers encounter during out work. I believe it's important to share these experiences that with the community to hopefully make other developers' job easier.



Summary of relevant offline professional activity: I participated in two panels during Sitecore Symposium this year in Orlando. I volunteered at the Sitecore Inspiration Booth that was part of Balance for Better initiative. I also paneled with Women of Sitecore: Facing key challenges in the digital and technology industry, and winning.

Live Projects: My roles varied from Sitecore Developer to Sitecore Architect. Sometimes I handle a certain section of the site and at other times I do discovery and plan/setup implementation starting with solution setup and architecture and configuring any tooling that comes with the implementation (serialization, code generation, etc).

In 2019 I, as part of the team, launched two large implementations (links below). My role was Architect where I did discovery, outlined the implementation plan and set up the solution and configured any tooling that comes with the implementation (serialization, code generation, etc), as well as took active role in development alongside other team members. My role is also largely client facing where I am responsible for interacting with clients to make sure their needs and requirements are met. I also mentor other team members and provide guidance and support where necessary.



Best Anecdote: One of my releases this year was a commerce site (Horizon Discovery) that offers 160 million (yes, million) product SKU's. Their commerce is mainly driven by search performed by scientific organizations and individual scientists and combines data from Sitecore and external non-sql databases. This was a very complex implementation but I was able to design and deliver their search process in a way that allows fast and relevant search. I developed custom ranking and boosting logic based on feedback by their customers to enhance their experience.



2019

I am currently a Sitecore MVP (Technology) and would like to maintain my MVP status. I am a Senior Sitecore developer with XCentium
and I build, maintain, and expand Sitecore sites of various sizes and complexity.
Olga is active in several technology groups and spends most of my waking hours coding, reading about coding, or discussing coding with others.



1. Padnug
2. Women who code

Went through Coveo for Sitecore training
Got certified for SC 9



1. IGT gaming
2. Assetmark
3. SFN


Plans:

building bridges between SC and other technologies (integrations)
Sitecore in the cloud

https://www.meetup.com/PADNUG/events/236094456/?eventId=236094456



with the move to CA present at local user groups (now only a member)




Horizon Discovery https://horizondiscovery.com/
Intuitive Surgical https://www.intuitive.com/en-us
Cessna Aircraft http://cessna.txtav.com/
Hawaiian Airlines https://www.hawaiianairlines.com/
Metropolitan Museum of Art https://www.metmuseum.org/
DOW Chemical https://www.dow.com/
Revlon http://www.revloncolorsilk.com/
IGT Gaming https://www.igt.com/
Society for Neuroscience's Brainfacts http://www.brainfacts.org/



Sunday, November 24, 2019

Abbreviations



DAM - Digital Marketing Assets

ERP - Enterprise Resource Planning (primarily to hold financial and logistical information)

PLM - Product Lifecycle Management (technical product specifications)

Product Information Management (PIM) or Product Content Management (PCM)

MRM
Marketing Resource Management (MRM) platforms, also known as campaign
management platforms, are a special guest here. These platforms are generally
used to support and measure the overall marketing cycle—from strategic
planning around budgeting, media planning, creative, review and annotation, to
execution, dropping final materials into the DAM, and measuring impact in the
publication channels.

Tuesday, November 19, 2019

Rename AD accounts on creation to have email


1. Add a pipeline

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Sitecore.Diagnostics;
using Sitecore.Owin.Authentication.Services;
using Sitecore.Owin.Authentication.Identity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Sitecore.Owin.Authentication.Configuration;

namespace Horizon.Foundation.Extensions.Pipeline
{
    public class CreateUniqueUser : DefaultExternalUserBuilder
    {
        public CreateUniqueUser(string isPersistentUser) : base(bool.Parse(isPersistentUser)) { }

        [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login")]
        protected override string CreateUniqueUserName(UserManager<ApplicationUser> userManager, ExternalLoginInfo externalLoginInfo)
        {
            Assert.ArgumentNotNull((object)userManager, nameof(userManager));
            Assert.ArgumentNotNull((object)externalLoginInfo, nameof(externalLoginInfo));
            IdentityProvider identityProvider = this.FederatedAuthenticationConfiguration.GetIdentityProvider(externalLoginInfo.ExternalIdentity);
            if (identityProvider == null)
            {
                Log.Error("Error in CreateUniqueUserName: identityProvider is null", this);
                throw new InvalidOperationException("Unable to retrieve identity provider for given identity");
            }           
               
            string domain = identityProvider.Domain;
            var emailClaim = externalLoginInfo.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "email");

            if(emailClaim != null)
                return domain + "\\" + emailClaim.Value;
           
            return domain + "\\" + "noname";
        }
    }
}

2. And a config patch

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:environment="http://www.sitecore.net/xmlconfig/environment/">
    <sitecore>
        <federatedAuthentication>
            <identityProvidersPerSites>
                <mapEntry name="all sites" type="Sitecore.Owin.Authentication.Collections.IdentityProvidersPerSitesMapEntry, Sitecore.Owin.Authentication">
                    <sites hint="list">
                        <site>regexp:.*</site>
                    </sites>
                    <!--<identityProviders hint="list:AddIdentityProvider">
                        <identityProvider ref="federatedAuthentication/identityProviders/identityProvider[@id='Facebook']"/>
                    </identityProviders>-->
                    <!--<externalUserBuilder type="Sitecore.Owin.Authentication.Services.DefaultExternalUserBuilder, Sitecore.Owin.Authentication">
                        <param desc="isPersistentUser">true</param>
                    </externalUserBuilder>-->
                    <externalUserBuilder type=" Horizon.Foundation.Extensions.Pipeline.CreateUniqueUser, Horizon.Foundation.Extensions">
                      <param desc="isPersistentUser">true</param>
                    </externalUserBuilder>
               
                </mapEntry>
            </identityProvidersPerSites>
        </federatedAuthentication>

Config patch for pdf redirect, broken RTE



1. X-Forwarded-For patches a header in n Sitecore.Analytics.Tracking.config. Needed for GeoIP.

2. Second in red needed for Redirects 301 module so that media library items also redirect. But needed to take axd out because RTE was broken, failing on missing handler RequestResource

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <settings>
            <setting name="Sitecore.Feature.Event.EventTypePath1" value="/sitecore/content/Horizon/Global/Event Type" />
            <setting name="Sitecore.Feature.Event.EventCountryPath1" value="/sitecore/content/Horizon/Global/Countries" />         
            <setting name="Analytics.ForwardedRequestHttpHeader">
                <patch:attribute name="value">X-Forwarded-For</patch:attribute>
            </setting>
        </settings>     
        <pipelines>
            <renderField>
                <processor
                    patch:after="*[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']"
                    type="Horizon.Foundation.Extensions.Pipeline.AddTitleToImages, Horizon.Foundation.Extensions"/>
            </renderField>
            <renderField>
                <processor
                    patch:before="processor[@type='Sitecore.Pipelines.RenderField.ExpandLinks, Sitecore.Kernel']"
                    type="Horizon.Foundation.Extensions.Pipeline.AddTitleToImagesInRTE, Horizon.Foundation.Extensions"/>
            </renderField>         
            <preprocessRequest>
                <processor type="Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel">
                    <param desc="Allowed extensions (comma separated)">aspx, ashx, asmx, pdf, xls, xlsx, txt</param>
                </processor>
            </preprocessRequest>
        </pipelines>
    </sitecore>
</configuration>

Multisite cache clearing

https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/clear-output-caches-for-all-managed-sites-after-publication-with-the-sitecore-asp-net-cms


IN a custom site def config. Sitecore cache is cleared for each site individually on each environment. If they are named the same. If sites are named differently each one needs a cache clear node.

 <events>
            <event name="publish:end">
                <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache">
                    <sites hint="list">
                        <site hint="horizon">horizon</site>
                    </sites>
                </handler>
            </event>
            <event name="publish:end:remote">
                <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache">
                    <sites hint="list">
                        <site hint="horizon">horizon</site>
                    </sites>
                </handler>
            </event>
        </events>
        <sites>
            <site name="horizon" environment:require="local" patch:after="site[@name='modules_website']"
                  hostName = "sc910.sc"
                  targetHostName="sc910.sc"
                  database="web"
                  virtualFolder="/"
                  physicalFolder="/"
                  rootPath="/sitecore/content/horizon"
                  startItem="/Home"
                  dictionaryPath="/sitecore/content/horizon/global/dictionary"
                  dictionaryAutoCreate="false"
                  placeholderSettingsRoot="/sitecore/layout/Placeholder Settings/Project/horizon"
                  domain="extranet"
                  allowDebug="true"
                  cacheHtml="true"
                  htmlCacheSize="50MB"
                  registryCacheSize="0"
                  viewStateCacheSize="0"
                  xslCacheSize="25MB"
                  filteredItemsCacheSize="10MB"
                  enablePreview="true"
                  enableWebEdit="true"
                  enableDebugger="true"
                  disableClientData="false"
                  cacheRenderingParameters="true"
                  renderingParametersCacheSize="10MB"
                  formsRoot="{4BC8A78C-44A7-46EB-8126-040D3F12CAA0}"
                  loginPage="/login"
                  scheme="http"
                  enableItemLanguageFallback="true" />
            <site name="horizon" environment:require="integration" patch:after="site[@name='modules_website']"
                  targetHostName="hd-rg53-www1-integration-280970-single.azurewebsites.net"
                  database="web"
                  virtualFolder="/"
                  physicalFolder="/"
                  rootPath="/sitecore/content/horizon"
                  startItem="/Home"
                  dictionaryPath="/sitecore/content/horizon/global/dictionary"
                  dictionaryAutoCreate="false"
                  placeholderSettingsRoot="/sitecore/layout/Placeholder Settings/Project/horizon"
                  domain="extranet"
                  allowDebug="true"
                  cacheHtml="true"
                  htmlCacheSize="50MB"
                  registryCacheSize="0"
                  viewStateCacheSize="0"
                  xslCacheSize="25MB"
                  filteredItemsCacheSize="10MB"
                  enablePreview="true"
                  enableWebEdit="true"
                  enableDebugger="true"
                  disableClientData="false"
                  cacheRenderingParameters="true"
                  renderingParametersCacheSize="10MB"
                  formsRoot="{4BC8A78C-44A7-46EB-8126-040D3F12CAA0}"
                  loginPage="/login"
                  scheme="https"
                  enableItemLanguageFallback="true" />

Monday, November 18, 2019

Sitecore misc modules of functionality and misc terms



WebDAV - Allows users to create, change and move documents on a
server

Federated Experience Manager,
Track visitor interactions and generate analytics
information on external, non-Sitecore websites from
within Sitecore.





XSLT Language used to transform XML

Performance tools



Google Page Speed Insights - https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fhorizondiscovery.com%2F

A browser plugin that analyses and grades performance of
websites.


Sitecore Azure PaaS

Roles


This is an optional role which publishes content from the master database to web database. It is a dedicated .Net core app that implements publishing mechanism different from the out of the box traditional way of publishing. It is designed to handle large amount of publishing tasks that could lead to performance issues using traditional publishing approach and could potentially improve high latency database environments such as cross regional data center connections.

EXM dispatch role is a core role that is combined with Content Management role out of the box. It is recommended to be setup as a dedicated role instance if there is decent amount of email dispatching jobs required for the platform. It must be combined with a content management role, does not run standalone and it supports horizontally scaling.
For details information, please ref to Sitecore Documentation site:
https://doc.sitecore.com/developers/92/platform-administration-and-architecture/en/exm-dispatch.html

Sitecore Universal Tracker services are Universal Tracking Collection service and Universal Tracking Processing service.
Sitecore Universal Tracker allows the collection of interaction data from different sources that are outside of Sitecore platform and processing of the collected data to be consumed by the Sitecore platform.
For product information, please ref to Sitecore Documentation site:
For service information, please ref to Sitecore Documentation site:
https://doc.sitecore.com/developers/92/platform-administration-and-architecture/en/universal-tracking-processing-service.html


Infrastructure Components


Content Delivery Network (CDN), in Sitecore context, it offloads media requests from Sitecore platform and allows the performance boost for static media asset requests potentially in multiple regions. Azure CDN is the CDN solution provided by Azure and it is supported by Sitecore 9.2.
The current environment setup does not contain CDN. If it is setup, it could improve the performances on content delivery servers by transferring all media requests onto CDN network and it is a suitable fit for a cross-region Sitecore platform setup as well.




Web Application Firewall (WAF) differs from regular network firewalls, it filters, monitors and blocks HTTP request traffic to and from a web application.
In Azure, Application Gateway (Azure AG) provides Web Application Firewall capabilities.
The current environment setup does not contain WAF or Azure AG. If it is implemented, it adds additional layer of security protection for Sitecore platform and offloads invalid traffic before they hit the actual content delivery server which in one way, it improves the performances of the public website.



Disaster recovery (DR) provides fall backs when primary environment became unavailable and enables faster recovery of the platform. There are different levels of disaster recovery that requires different amount of effort and in returns, provide different level of experiences for end users when the website services are accessed during the events.
There are some limitations and considerations as well why setting up DR within Azure infrastructure, please ref to the Sitecore documentation (linked below) for more details.
The current environment setup does not contain disaster recovery. If it is implemented, it could reduce the downtime if any unforeseen outages occur within the Azure infrastructures of current region.
For more details, please ref to Sitecore official documentation: https://kb.sitecore.net/articles/133741

Thursday, November 14, 2019

Integating FE repo into BE

FE gets its own folder in the BE solution

FE assets are added to the project but physical files are not there. With build dist folder gets generated and files are copied where they need to be.

Then





Check that in, build, deploy. Then

[12:43 PM] Adam Bezemek
cd FE
​
[12:44 PM] Adam Bezemek
npm install (first-time)
​
[12:44 PM] Adam Bezemek
npm run build:sitecore (latest FE assets in Sitecore Solution)

Friday, September 27, 2019

Search suggestions and highlights

I needed to provide search term suggestions based on characters that the user has typed into the search box. Doing this is pretty easy with Solr, an open source enterprise search platform, powered by Java, Apache and Lucene.

If you’re using a version prior to 4.8, this can be accomplished using the SpellCheckComponent. See this document for details.

As of 4.8 a new component is available, the solr.SuggestComponent. This post will go through the steps to configure an index to provide search suggestions using this component. In my case I created a separate index to handle this, it could be combined into an existing index such as sitecore_web_index (or any other custom indexes you may be using), depending on what your needs are.

Define the schema for the index:
In order to create smaller documents I trimmed the fields down to the bare minimums. This is done in schema.xml.

[code language=”xml”]
<fields>
<field name="_content" type="text_general" indexed="true" stored="false" />
<field name="_database" type="string" indexed="true" stored="true" />
<field name="_uniqueid" type="string" indexed="true" stored="true" required="true" />
<field name="_name" type="text_general" indexed="true" stored="true" />
<field name="_indexname" type="string" indexed="true" stored="true" />
<field name="_version" type="string" indexed="true" stored="true" />
<field name="_version_" type="long" indexed="true" stored="true" />
</fields>
[/code]

Then I added two fields that will be used by the suggester. One to store the suggestion text and another to store the weight of that suggestion. The suggestion field should be a text type and the weight field should be a float type. Both need to be stored in the index. In this case these fields get their values form corresponding fields in our sitecore instance. These fields can be added to documents based on your specific indexing strategy.

[code language=”xml”]
<field name="term" type="text_general" indexed="true" stored="true" />
<field name="weight" type="float" indexed="true" stored="true" />
[/code]

Define a custom field type for the suggest component:
Next we need to add a new type that the suggester will use to analyze and build the suggestion fields. This particular type will remove all non alphanumeric characters and be case-insensitive as well as tokenizing the contents of the field. This is not strictly necessary, existing types may be used. Again, this is done in schema.xml.

[code language=”xml”]
<types>
…
<fieldType name="suggestType" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[^a-zA-Z0-9]" replacement=" " />
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
…
</types>
[/code]

Define the suggest component for the index:
Now that we have the schema set up, we need to define a searchComponent that will do the suggesting. This is done in solrconfig.xml.

Add the following to the <config> node:

[code language=”xml”]
<searchComponent name="suggest" class="solr.SuggestComponent">
<lst name="suggester">
<str name="name">fuzzySuggester</str>
<str name="lookupImpl">FuzzyLookupFactory</str>
<str name="storeDir">fuzzy_suggestions</str>
<str name="dictionaryImpl">DocumentDictionaryFactory</str>
<str name="field">term</str>
<str name="weightField">weight</str>
<str name="suggestAnalyzerFieldType">suggestType</str>
<str name="buildOnStartup">false</str>
<str name="buildOnCommit">false</str>
</lst>
<lst name="suggester">
<str name="name">infixSuggester</str>
<str name="lookupImpl">AnalyzingInfixLookupFactory</str>
<str name="indexPath">infix_suggestions</str>
<str name="dictionaryImpl">DocumentDictionaryFactory</str>
<str name="field">term</str>
<str name="weightField">weight</str>
<str name="suggestAnalyzerFieldType">suggestType</str>
<str name="buildOnStartup">false</str>
<str name="buildOnCommit">false</str>
</lst>
</searchComponent>
[/code]

lookupImpl
In this case we’re setting up a suggest component that has two suggester data sources available to it.

The first uses the FuzzyLookupFactory: a FST-based sugester (Finite State Transducer) which will match terms starting with the provided characters while accounting for potential misspellings. This lookup implementation will not find terms where the provided characters are in the middle.
The second uses the AnalyzingInfixLookupFactory: which will look inside the terms for matches. Also the results will have <b> highlights around the provided terms inside the suggestions.
Using a combination of methods, we can get more complete results. Additional suggester implementations are available:

WFSTLookup: offers more fine-grained control over results ranking than FST
TSTLookup: “a simple, compact trie-based lookup”. Whatever that means.
JaspellLookup: see the Jaspell source.
See the Suggester Documentation for more details on the different types of Lookup Implementations. They each have properties unique to their implementation.

storeDir and indexPath
These parameters define the directory where the suggester structure will be stored after it’s built. This parameter should be set so the data is available on disc without rebuilding.

field
The field to get the suggestions from. This could be a computed or a copy field.

weightField
As of Solr 5.1 this field is optional. In previous versions this field is required. If no proper weight value is available, a workaround is to define a float field in your schema and use that. Even if this field is never added to a document the code will compensate.

threshold (not used in this example)
A percentage of the documents a term must appear in. This can be useful for reducing the number of garbage returns due to misspellings if you haven’t scrubbed the input.

suggestAnalyzerFieldType
This parameter is set to the fieldType that will process the information in the defined ‘field’. I suggest starting simple and adding complexity as the need arises.

This fieldType is completely independent from the analysis chain applied to the field you specify for your suggester. It’s perfectly reasonable to have the two fieldTypes be much different.
The “string” fieldType should probably not be used. If a “string” type is appropriate for the use case, the TermsComponent will probably serve as well and it is much simpler.
buildOnStartup and buildOnCommit
Building the suggester data involves re-reading, decompressing and and adding the field from every document to the suggester. These two settings should both generally be set to “false”. On Startup happens every time Solr is started. On Commit happens every time a document is committed. In the case of a smaller list of potential suggestions, the latter is acceptable.

Define a requestHandler for the Suggest Component
[code language=”xml”]
<requestHandler name="/suggest" class="solr.SearchHandler" startup="lazy" >
<lst name="defaults">
<str name="suggest">true</str>
<str name="suggest.dictionary">infixSuggester</str>
<str name="suggest.dictionary">fuzzySuggester</str>
<str name="suggest.onlyMorePopular">true</str>
<str name="suggest.count">10</str>
<str name="suggest.collate">true</str>
</lst>
<arr name="components">
<str>suggest</str>
</arr>
</requestHandler>
[/code]

The “name” of the requestHandler defines the url that will be used to request suggestions. In this case it will be http://”localhost”:8983/solr/index_name/suggest. Your port number may be different.

The requestHandler definition contains two parts:

defaults
These are settings that you would like to apply to each request. They may be provided in the querystring if different values are necessary.

Multiple “suggest.dictionary” values may be used. Each one will have it’s own section of results. The values are the names of the suggesters that were defined in the Suggest Component.

components
The name of the Suggest Component is set here. This connects the handler to the component.

See the documentation for more details on configuring search components and request handlers.

Actually getting suggestions
Once all of this is set up, using it is very simple. Assuming a solr index url like this:
http://localhost:8983/solr/index_name

Build the suggester:
Issue http://localhost:8983/solr/index_name/suggest?suggest.build=true.
Until you do this step, no suggestions are returned.
The two build settings (buildOnStartup and buildOnCommit) can be used to avoid this, but consider the size of your index and the time and cpu that will be required to build the suggest index automatically.
Ask for suggestions:
Issue http://localhost:8983/solr/index_name/suggest?suggest.q=whatever
Additional parameters can be included, such as the count, the desired format (json or xml) or a specific suggest.dictionary.
Use “wt” and “indent” parameters to format your results into json or xml and apply indenting. e.g.: &wt=json&indent=true
The response will contain a “suggest” field. This field will contain fields for each of the suggest.dictionaries that was used. Each of these dictionary fields will have a “numFound” field as well as a “suggestions” field containing an array of the found suggestions and their weights.
Response Format:

[code language=”js”]
{
suggest: {
suggester_name: {
suggest_query: { numFound: .., suggestions: [ {term: .., weight: .., payload: ..}, .. ]}
}
}
[/code]

I hope you find this information useful. See the Suggester documentation for more details.

Thanks for reading!

Category
SITECORE FOR DEVELOPERS
 
BY NATE HASE
Programmer, Gamer, Mammal


RELATED CONTENT
KEY CAVEATS WHILE CONFIGURING SOLRCLOUD WITH SITECORE
SITECORE DROP LIST FACETING PHRASE SPACE ISSUE WITH SOLR SEARCH
SOLR CORE CONFIGURATION CONSIDERATIONS
RECENT POSTS
Getting started with B2B onsite personalization
Sitecore’s RuleValidator for validating multiple fields at once
4 Strategic Initiatives to Help You Prepare for the Future of Personalization
Inside Horizontal: Tessa Wolff
Sitecore commerce Translate Shipping Party to Engine Entity
DIGITAL AGENCY
Acquia
AI
Analytics
Cloud Infrastructure
Commerce
Digital Agency
Digital strategy
Drupal
Dubai
India
Marketing Automation
Marketing Cloud
Personalization
Salesforce
Site Optimization
Sitecore
Sitecore Experience Accelerator
Sitecore for Developers
FOLLOW US
Instagram

Facebook

LinkedIn

Twitter
staffing
Let's put your talents to work

FIND A JOB
digital agency
Enhance your digital presence

WORK WITH US
Contact Us
©2019 Horizontal Integration

Privacy Policy  | Disclaimer  Horizontal Integration is an Affirmati

SOLR suggestions spellchecking and search


https://lucene.apache.org/solr/guide/6_6/suggester.html

The two files in involved:


C:\Program Files\solr-7.2.1\server\solr\sc910_web_index\conf\managed-schema

Add another field type:

<fieldType name="suggestTypeLc" class="solr.TextField" positionIncrementGap="100">

  <analyzer>
<charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[^a-zA-Z0-9]" replacement=" " />
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>


C:\Program Files\solr-7.2.1\server\solr\sc910_web_index\conf\solrconfig.xml (before cliosing </config>)

<searchComponent name="suggest" class="solr.SuggestComponent">

    <lst name="suggester">
      <str name="name">mySuggester</str>
      <str name="lookupImpl">FreeTextLookupFactory</str>
      <str name="dictionaryImpl">DocumentDictionaryFactory</str>
      <str name="field">producttext_t</str>
      <str name="ngrams">3</str>
      <str name="separator"> </str>
      <str name="suggestFreeTextAnalyzerFieldType">suggestTypeLc</str>
    </lst>
  </searchComponent>
  <requestHandler name="/suggest" class="solr.SearchHandler" startup="lazy">
    <lst name="defaults">
      <str name="suggest">true</str>
      <str name="suggest.count">5</str>
      <str name="suggest.dictionary">mySuggester</str> 
    </lst>
    <arr name="components">
      <str>suggest</str>
    </arr>
  </requestHandler>



Code:

using Sitecore;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.Linq.Utilities;
using Sitecore.ContentSearch.SolrNetExtension;
using Sitecore.ContentSearch.SolrProvider.SolrNetIntegration;
using Sitecore.ContentSearch.Utilities;
using Sitecore.Diagnostics;
using Sitecore.Links;
using Sitecore.Resources.Media;


 public IEnumerable<SitecoreSearchSuggestion> GetTopLevelSuggestions(string term)
        {
            try
            {             

                //sitecore suggestions
                using (IProviderSearchContext ctx = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
                {
                    SolrSuggestQuery q = term;
                    SuggestHandlerQueryOptions options = new SuggestHandlerQueryOptions
                    {
                        Parameters = new SuggestParameters
                        {
                            Count = 3,
                            Build = true
                        }
                    };
                    SolrSuggestHandlerQueryResults result = ctx.Suggest(q, options);

                    IEnumerable<SitecoreSearchSuggestion> sitecoreSuggestionsResults = result.Suggestions["mySuggester"].Suggestions.Select(i =>
                   new SitecoreSearchSuggestion()
                   {
                       Value = i.Term
                   });

                    return sitecoreSuggestionsResults;
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error fetching top level search suggestions - " + ex.Message, ex, this);
                return null;
            }
        }

Build suggestions:

https://localhost:8983/solr/index_name/suggest?suggest.build=true

Example: https://localhost:8983/solr/sc910_web_index/suggest?suggest.build=true


Get suggestions:

 http://localhost:8983/solr/index_name/suggest?suggest.q=whatever

=============================

Fuzzy search

https://horizontalintegration.blog/2015/07/20/configuring-solr-to-provide-search-suggestions/

Spell Checker

https://doc.sitecore.com/developers/90/platform-administration-and-architecture/en/using-the-solr-spell-checker.html#

Linq


1. Checks if any of the items in the list are also contained in another list

- Flattens our .Filters object to get ID's
- Checks if any of the filter ID's are in the list of tagGuids (array of guids)

string[] tagGuids = new string[] { };

            if (!string.IsNullOrEmpty(tags))
            {
                tagsPredicate = PredicateBuilder.False<ProductSearchItem>();
                tagGuids = tags.Split(',');

                foreach (string tagGuidString in tagGuids)
                {
                    Guid tagGuid = Guid.Parse(tagGuidString);
                    tagsPredicate = tagsPredicate.Or(p => p.ContentTags.Contains(tagGuid));
                }
            }



                _HapiResults = new ProductSearchController().GetProductCategorySearchResults(searchTerm, cartContext)
                    .Where(x => tagGuids.Any(t => x.Filters.Select(f => f.Id).Contains(t))).ToList(); 



2. Select new

unifiedProducts.AddRange(_AllNonProductResults.Select(e => new UnifiedProduct
                    {
                        Name = (!string.IsNullOrEmpty(e.ProductTitle)) ? e.ProductTitle : e.Title,
                        PifType = (!string.IsNullOrEmpty(e.Pif_Type)) ? e.Pif_Type : string.Empty,
                        IsGeneric = (IsNotProductOrGene(e)) ? true : false,
                        Description = StringUtil.Clip(e.Teaser_Text, 350, true),
                        Url = e.Url,
                        ExactMatchResult = null,
                        GeneNodeId = (!string.IsNullOrEmpty(e.ProductTitle)) ? e.ProductTitle : e.Title,
                        Symbol = null
                    }).ToList());


3. SelectMany (flattens out second layer list)

 List<Filter> hapiFilters = hapiModel.Results
                 .SelectMany(r => r.Filters)
                 .GroupBy(f => f.Item1)
                 .Select(fg => new Filter()
                 {
                     FilterName = fg.Key,
                     FilterItems = fg.GroupBy(fi => fi.Item2).Select(fi => new FilterItem()
                     {
                         FilterItemName = fi.Key,
                         FIlterItemGuid = fi.Key,
                         Count = fg.Count()
                     }).ToList()
                 }).ToList();

Friday, August 30, 2019

Content search with boosting and relevancy sort

http://www.ehabelgindy.com/sitecore-7-solr-sorting-search-results-by-score/


Best way:
//Do sorting and paging in solr, before results are retrieved
                 using (IProviderSearchContext context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
            {
                //Do sorting and paging in solr, before results are retrieved
                SearchResults<ProductSearchItem> result = context.GetQueryable<ProductSearchItem>().Where(query)
                    .FacetOn(t => t["content_tags_sm"], 1)// append as many.FacetOn() as needed
                    .OrderByDescending(x => x["score"])
                    .Skip(intSkip).Take(intPageSize).GetResults();
                model.NumFound = result.TotalSearchResults.ToString();
                //results = result.Hits.OrderByDescending(x => x.Score).Select(p => p.Document);
                results = result.Hits.Select(p => p.Document);
                model.Facets = result.Facets;
            }

But doing .Score (commented out) is less efficient

Sitecore 7 & Solr – Sorting Search Results by Score



Share Button
TwitterFacebookPinterestLinkedin
The Solr search provider in Sitecore 7 allows users to rank the search results using different types of boosting methods. This article shows how to use the Query-Time Boosting to sort the search results and highlights the common mistakes that developers should avoid.
Assume that you want to run a search query over a set of Sitecore items, each of which has a title and description fields, and you would like the score of the results that contain the search keyword in the title to be higher than the ones contain the search keyword in the description.
The search query that uses Query-Time Boosting should look like:
  1. var query = "guitar";
  2. var dataQuery = context.GetQueryable<SearchResultItem>()
  3. .Where(i => i.Title == query.Boost(3.0f) || i.Description == query.Boost(1.0f))

The generated Solr query will be:
q=(title_t:(guitar))^3 OR  page_body_t:(guitar))&fl=*,score
The query uses the ^ operator to specify the boosting value. As Solr doesn’t return the score values by default, the “fl=*,score” query string tells Solr to return all the default fields + the score field.
Back to your Sitecore code, the score values can be retrieved using the SearchHit object as follows:
dataQuery.GetResults().Hits.First().Score;
Which will get the score of the first search result.

Mistake – Using LINQ to Objects

One big sin that a developer can commit is to use LINQ to objects to sort the search results as follows:
var results = dataQuery.GetResults().Hits.OrderByDescending(h => h.Score).Select(h => h.Document);
The above query will retrieve the results from Solr and sort them in memory. This is a very bad coding practice even if the returned data set is small, all the sorting logic should be handled by Solr. This code can be even worse if you want to add pagination to your search results as follows:
var results = dataQuery.Page(page,pageSize).GetResults().Hits.OrderByDescending(h => h.Score).Select(h => h.Document);
The above code will do the pagination on Solr and then will sort each page on the web server!!

The Right Way

To sort the search results on Solr you will need to write the following query:
  1. dataQuery = dataQuery.OrderByDescending(i => i["score"]);
  2. var results = dataQuery.GetResults().Hits.Select(h => h.Document);

This will generate the following query, notice the sort sort query string.
q=(title_t:(guitar))^3 OR page_body_t:(guitar))&sort=score desc&fl=*,score

Sort Using Multiple Fields

In some cases you may need to use a secondary sort field, having the score field as your main sorting field. So, your query should look like:
  1. dataQuery = dataQuery.OrderByDescending(i => i["score"]).ThenByDescending(i => i.Title);
  2. var results = dataQuery.GetResults().Hits.Select(h => h.Document);
This code won’t work as expected; due to a bug in the Sitecore search provider, the parameter of the ThenBy will go before the parameter of the OrderBy. Hence your query should be:
  1. dataQuery = dataQuery.OrderByDescending(i => i.Title).ThenByDescending(i => i["score"]);
  2. var results = dataQuery.GetResults().Hits.Select(h => h.Document);