Sitecore 9
has an OOTB extension GetMoreLikeThis for the IProviderSearchContext
. To use it you need to install the SolrNet
nuget package. You can use it like following:
var contextIndex = _contextRepository.GetSearchIndexContext("search_index");
using (var context = contextIndex.CreateSearchContext())
{
var parameters = new MoreLikeThisHandlerParameters(new[] {"field1", "field2"})
{
MinDocFreq = 1, // minimum document frequency
MinTermFreq = 1, // minimum term frequency
};
var query = SolrMLTQuery.FromQuery(new SolrQuery("search_term"));
var queryOption = new MoreLikeThisHandlerQueryOptions(parameters);
var results = context.GetMoreLikeThis<SearchResultItem>(query, queryOption);
var interestingTerms = results.InterestingTerms;
}
Alternatively, you can use a native SorlNet
query:
var contextIndex = _contextRepository.GetSearchIndexContext("search_index");
using (var context = contextIndex.CreateSearchContext())
{
var results = context.Query<SearchResultItem>(new SolrQuery("search_term"), new QueryOptions
{
MoreLikeThis = new MoreLikeThisParameters(new[] { "field1", "field2" })
{
MinDocFreq = 1, // minimum document frequency
MinTermFreq = 1, // minimum term frequency
},
});
var similarResults = results.SimilarResults;
}
If you use LINQ
-based predicates and they are complex and you can not rewrite your queries to SolrNet
-based, you can use this "hack" to convert them. But keep in mind that in this case one additional request will be sent to Solr:
var linqQuery = context.GetQueryable<SearchResultItem>().Where(predicate);
var solrNetQuery = new SolrQuery(((IHasNativeQuery)linqQuery).Query.ToString());