This blog represents how to get the total number of times a particular term exists in a field in while searching from solr.
Suppose you have an index and have populated some document in the index , and in the documents , you have a field _content , which is of text_general type , and from that field you want to search a term immigration .
To search immigration , in the Solr Admin , write the query
q=_content:("immigration") and execute the query , but if you also want to sort the results on the basis of relevancy , that how often that term appears in the document , then you have to use
termfreq function.
Syntax Examples :-
termfreq(fieldname,'term')
To achieve that , in the sort field in solr admin , write
termfreq("_content","immigration") desc (for descending)
and in the fl field write
_displayname,termfreq(_content,"immigration") desc
to show the Display Name of each document and also the number of hits of the keyword immigration in each field .
Solr sorts the results based on the relevancy of the term present in the field OOTB (it uses tf-idf algorithm to calculate scoring).
How to achieve this programatically -
using (var context = ContentSearchManager.GetIndex("contentIndex").CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
{
var queryableResultItems = context.GetQueryable<GlobalSearchResultItem >()
.Where(expression)
.OrderByDescending(x => x["termfreq(_content," + text.Trim() + ")"]);
}
Note -
Your field on which you want to perform search operations should be tokenized .
Suppose you have an index and have populated some document in the index , and in the documents , you have a field _content , which is of text_general type , and from that field you want to search a term immigration .
To search immigration , in the Solr Admin , write the query
q=_content:("immigration") and execute the query , but if you also want to sort the results on the basis of relevancy , that how often that term appears in the document , then you have to use
termfreq function.
Syntax Examples :-
termfreq(fieldname,'term')
To achieve that , in the sort field in solr admin , write
termfreq("_content","immigration") desc (for descending)
and in the fl field write
_displayname,termfreq(_content,"immigration") desc
to show the Display Name of each document and also the number of hits of the keyword immigration in each field .
Solr sorts the results based on the relevancy of the term present in the field OOTB (it uses tf-idf algorithm to calculate scoring).
How to achieve this programatically -
using (var context = ContentSearchManager.GetIndex("contentIndex").CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
{
var queryableResultItems = context.GetQueryable<GlobalSearchResultItem >()
.Where(expression)
.OrderByDescending(x => x["termfreq(_content," + text.Trim() + ")"]);
}
Note -
Your field on which you want to perform search operations should be tokenized .
Comments
Post a Comment