Using Solr queries in Solr4J
Posted By : Jasgeet Singh | 29-Apr-2013
I learned a few things about using Solr Queries in a project where we used Solr4J and Solr full Text search. I am blogging about some of my learnings on How to use Solr Queries here . If you are not aware about Solr Search Engine, you can read about the same from link here:
I will start with some examples
Example 1: If we have facet Company Type which has some facet values like Retail, Accommodation, Travels & Construction and facet Specialities. We want the result where all company types must have at least one speciality except Accommodation.
def solrQuery = new SolrQuery ("*”)
solrQuery.addField("company_type")
solrQuery.addField("specialities")
solrQuery.addFilterQuery("((+category: Retail) AND (specialities: [* TO *])) OR (category :( Accommodation)) OR ((category: Travels) AND (specialities: [* TO *])) OR ((category: Construction) AND (specialities: [* TO *]))")
Example 2: If we want to find search terms not from whole document only from some facets.
def solrQuery = new SolrQuery ("*”)
solrQuery.addField ("location")
solrQuery.addField ("city")
solrQuery.addField ("country")
def filterQuery = / (location: "searchTerm"+*) OR (city: "searchTerm"+*) OR (country: "searchTerm"+*)/"
solrQuery.addFilterQuery (filterQuery)
Here at line no 9, I add “*” with the search term, it means we find the search term from facets containing the words starting with “search terms”. It must to add in order to refine your searching.
Example 3: How to get all facet values that particular facet contains.
SolrQuery solrQuery = new SolrQuery ("*")
solrQuery.add("wt","json")
solrQuery.add("json.nl", "map")
solrQuery.setRows(0)
solrQuery.setFacet(true)
solrQuery.addFacetField("company_type")
From this query you get the JSONObject containing facet company_type as key and its facet values.
Existence (and non-existence) queries:
This is actually not a new syntax case, but an application of range queries. Suppose you wanted to match all of the documents that have an indexed value in a field. Here we find all of the documents that have something in facet Employee_Name:
Employee_Name: [* TO *]
This can be negated to find documents that do not have a value for Employee_Name, as shown in the following code:
- Employee_Name: [* TO *]
Hope it helps!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Jasgeet Singh
Jasgeet is a Sr. Lead developer .He is an experienced Groovy and Grails and has worked on designing & developing B2B and B2C portals using Grails technologies.