Apache Solr Documentation

6.5 Ref Guide (PDF Download)
Solr Tutorial
Solr Community Wiki

Older Versions of this Guide (PDF)

6.6 Draft Ref Guide Topics

Meta-Documentation

This Unreleased Guide Covers Apache Solr 6.6
As of 5 May 2017, committer editing of this Ref Guide is LOCKED for migration to the new Ref Guide. See SOLR-10290 for details.

Skip to end of metadata
Go to start of metadata

Solr's default Query Parser is also known as the "lucene" parser.

The key advantage of the standard query parser is that it supports a robust and fairly intuitive syntax allowing you to create a variety of structured queries. The largest disadvantage is that it's very intolerant of syntax errors, as compared with something like the DisMax query parser which is designed to throw as few errors as possible.

Topics covered in this section:

Standard Query Parser Parameters

In addition to the Common Query Parameters, Faceting Parameters, Highlighting Parameters, and MoreLikeThis Parameters, the standard query parser supports the parameters described in the table below.

Parameter

Description

q

Defines a query using standard query syntax. This parameter is mandatory.

q.op

Specifies the default operator for query expressions, overriding the default operator specified in the Schema. Possible values are "AND" or "OR".

df

Specifies a default field, overriding the definition of a default field in the Schema.

sowSplit on whitespace: if set to false, whitespace-separated term sequences will be provided to text analysis in one shot, enabling proper function of analysis filters that operate over term sequences, e.g. multi-word synonyms and shingles. Defaults to true: text analysis is invoked separately for each individual whitespace-separated term.

Default parameter values are specified in solrconfig.xml, or overridden by query-time values in the request.

The Standard Query Parser's Response

By default, the response from the standard query parser contains one <result> block, which is unnamed. If the debug parameter is used, then an additional <lst> block will be returned, using the name "debug". This will contain useful debugging info, including the original query string, the parsed query string, and explain info for each document in the <result> block. If the explainOther parameter is also used, then additional explain info will be provided for all the documents matching that query.

Sample Responses

This section presents examples of responses from the standard query parser.

The URL below submits a simple query and requests the XML Response Writer to use indentation to make the XML response more readable.

http://localhost:8983/solr/techproducts/select?q=id:SP2514N

Results:

Here's an example of a query with a limited field list.

Results:

Specifying Terms for the Standard Query Parser

A query to the standard query parser is broken up into terms and operators. There are two types of terms: single terms and phrases.

  • A single term is a single word such as "test" or "hello"
  • A phrase is a group of words surrounded by double quotes such as "hello dolly"

Multiple terms can be combined together with Boolean operators to form more complex queries (as described below).

It is important that the analyzer used for queries parses terms and phrases in a way that is consistent with the way the analyzer used for indexing parses terms and phrases; otherwise, searches may produce unexpected results.

Term Modifiers

Solr supports a variety of term modifiers that add flexibility or precision, as needed, to searches. These modifiers include wildcard characters, characters for making a search "fuzzy" or more general, and so on. The sections below describe these modifiers in detail.

Wildcard Searches

Solr's standard query parser supports single and multiple character wildcard searches within single terms. Wildcard characters can be applied to single terms, but not to search phrases.

Wildcard Search Type

Special Character

Example

Single character (matches a single character)

?

The search string te?t would match both test and text.

Multiple characters (matches zero or more sequential characters)

*

The wildcard search:

tes*

would match test, testing, and tester.

You can also use wildcard characters in the middle of a term. For example:

te*t

would match test and text.

*est

would match pest and test.

Fuzzy Searches

Solr's standard query parser supports fuzzy searches based on the Damerau-Levenshtein Distance or Edit Distance algorithm. Fuzzy searches discover terms that are similar to a specified term without necessarily being an exact match. To perform a fuzzy search, use the tilde ~ symbol at the end of a single-word term. For example, to search for a term similar in spelling to "roam," use the fuzzy search:

roam~

This search will match terms like roams, foam, & foams. It will also match the word "roam" itself.

An optional distance parameter specifies the maximum number of edits allowed, between 0 and 2, defaulting to 2.  For example:

roam~1

This will match terms like roams & foam - but not foams since it has an edit distance of "2".

In many cases, stemming (reducing terms to a common stem) can produce similar effects to fuzzy searches and wildcard searches.

Proximity Searches

A proximity search looks for terms that are within a specific distance from one another.

To perform a proximity search, add the tilde character ~ and a numeric value to the end of a search phrase. For example, to search for a "apache" and "jakarta" within 10 words of each other in a document, use the search:

"jakarta apache"~10

The distance referred to here is the number of term movements needed to match the specified phrase. In the example above, if "apache" and "jakarta" were 10 spaces apart in a field, but "apache" appeared before "jakarta", more than 10 term movements would be required to move the terms together and position "apache" to the right of "jakarta" with a space in between.

Range Searches

A range search specifies a range of values for a field (a range with an upper bound and a lower bound). The query matches documents whose values for the specified field or fields fall within the range. Range queries can be inclusive or exclusive of the upper and lower bounds. Sorting is done lexicographically, except on numeric fields. For example, the range query below matches all documents whose mod_date field has a value between 20020101 and 20030101, inclusive.

mod_date:[20020101 TO 20030101]

Range queries are not limited to date fields or even numerical fields. You could also use range queries with non-date fields:

title:{Aida TO Carmen}

This will find all documents whose titles are between Aida and Carmen, but not including Aida and Carmen.

The brackets around a query determine its inclusiveness.

  • Square brackets [ ] denote an inclusive range query that matches values including the upper and lower bound.
  • Curly brackets { } denote an exclusive range query that matches values between the upper and lower bounds, but excluding the upper and lower bounds themselves.
  • You can mix these types so one end of the range is inclusive and the other is exclusive.  Here's an example: count:{1 TO 10]

Boosting a Term with ^

Lucene/Solr provides the relevance level of matching documents based on the terms found. To boost a term use the caret symbol ^ with a boost factor (a number) at the end of the term you are searching. The higher the boost factor, the more relevant the term will be.

Boosting allows you to control the relevance of a document by boosting its term. For example, if you are searching for

"jakarta apache" and you want the term "jakarta" to be more relevant, you can boost it by adding the ^ symbol along with the boost factor immediately after the term. For example, you could type:

jakarta^4 apache

This will make documents with the term jakarta appear more relevant. You can also boost Phrase Terms as in the example:

"jakarta apache"^4 "Apache Lucene"

By default, the boost factor is 1. Although the boost factor must be positive, it can be less than 1 (for example, it could be 0.2).

Constant Score with ^=

Constant score queries are created with <query_clause>^=<score>, which sets the entire clause to the specified score for any documents matching that clause.  This is desirable when you only care about matches for a particular clause and don't want other relevancy factors such as term frequency (the number of times the term appears in the field) or inverse document frequency (a measure across the whole index for how rare a term is in a field).

Example:

(description:blue OR color:blue)^=1.0 text:shoes

Specifying Fields in a Query to the Standard Query Parser

Data indexed in Solr is organized in fields, which are defined in the Solr Schema. Searches can take advantage of fields to add precision to queries. For example, you can search for a term only in a specific field, such as a title field.

The Schema defines one field as a default field. If you do not specify a field in a query, Solr searches only the default field. Alternatively, you can specify a different field or a combination of fields in a query.

To specify a field, type the field name followed by a colon ":" and then the term you are searching for within the field.

For example, suppose an index contains two fields, title and text,and that text is the default field. If you want to find a document called "The Right Way" which contains the text "don't go this way," you could include either of the following terms in your search query:

title:"The Right Way" AND text:go

title:"Do it right" AND go

Since text is the default field, the field indicator is not required; hence the second query above omits it.

The field is only valid for the term that it directly precedes, so the query title:Do it right will find only "Do" in the title field. It will find "it" and "right" in the default field (in this case the text field).

Boolean Operators Supported by the Standard Query Parser

Boolean operators allow you to apply Boolean logic to queries, requiring the presence or absence of specific terms or conditions in fields in order to match documents. The table below summarizes the Boolean operators supported by the standard query parser.

Boolean Operator

Alternative Symbol

Description

AND

&&

Requires both terms on either side of the Boolean operator to be present for a match.

NOT

!

Requires that the following term not be present.

OR

||

Requires that either term (or both terms) be present for a match.

 

+

Requires that the following term be present.

 

-

Prohibits the following term (that is, matches on fields or documents that do not include that term). The - operator is functionally similar to the Boolean operator !. Because it's used by popular search engines such as Google, it may be more familiar to some user communities.

Boolean operators allow terms to be combined through logic operators. Lucene supports AND, "+", OR, NOT and "-" as Boolean operators.

When specifying Boolean operators with keywords such as AND or NOT, the keywords must appear in all uppercase.

The standard query parser supports all the Boolean operators listed in the table above. The DisMax query parser supports only + and -.

The OR operator is the default conjunction operator. This means that if there is no Boolean operator between two terms, the OR operator is used. The OR operator links two terms and finds a matching document if either of the terms exist in a document. This is equivalent to a union using sets. The symbol || can be used in place of the word OR.

To search for documents that contain either "jakarta apache" or just "jakarta," use the query:

"jakarta apache" jakarta

or

"jakarta apache" OR jakarta

The Boolean Operator +

The + symbol (also known as the "required" operator) requires that the term after the + symbol exist somewhere in a field in at least one document in order for the query to return a match.

For example, to search for documents that must contain "jakarta" and that may or may not contain "lucene," use the following query:

+jakarta lucene

This operator is supported by both the standard query parser and the DisMax query parser.

The Boolean Operator AND (&&)

The AND operator matches documents where both terms exist anywhere in the text of a single document. This is equivalent to an intersection using sets. The symbol && can be used in place of the word AND.

To search for documents that contain "jakarta apache" and "Apache Lucene," use either of the following queries:

"jakarta apache" AND "Apache Lucene"

"jakarta apache" && "Apache Lucene"

The Boolean Operator NOT (!)

The NOT operator excludes documents that contain the term after NOT. This is equivalent to a difference using sets. The symbol ! can be used in place of the word NOT.

The following queries search for documents that contain the phrase "jakarta apache" but do not contain the phrase "Apache Lucene":

"jakarta apache" NOT "Apache Lucene"

"jakarta apache" ! "Apache Lucene"

The Boolean Operator -

The - symbol or "prohibit" operator excludes documents that contain the term after the - symbol.

For example, to search for documents that contain "jakarta apache" but not "Apache Lucene," use the following query:

"jakarta apache" -"Apache Lucene"

Escaping Special Characters

Solr gives the following characters special meaning when they appear in a query:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : /

To make Solr interpret any of these characters literally, rather as a special character, precede the character with a backslash character \. For example, to search for (1+1):2 without having Solr interpret the plus sign and parentheses as special characters for formulating a sub-query with two terms, escape the characters by preceding each one with a backslash:

Grouping Terms to Form Sub-Queries

Lucene/Solr supports using parentheses to group clauses to form sub-queries. This can be very useful if you want to control the Boolean logic for a query.

The query below searches for either "jakarta" or "apache" and "website":

(jakarta OR apache) AND website

This adds precision to the query, requiring that the term "website" exist, along with either term "jakarta" and "apache."

Grouping Clauses within a Field

To apply two or more Boolean operators to a single field in a search, group the Boolean clauses within parentheses. For example, the query below searches for a title field that contains both the word "return" and the phrase "pink panther":

title:(+return +"pink panther")

Comments

C-Style comments are supported in query strings.

Example:

"jakarta apache" /* this is a comment in the middle of a normal query string */ OR jakarta

Comments may be nested.

Differences between Lucene Query Parser and the Solr Standard Query Parser

Solr's standard query parser differs from the Lucene Query Parser in the following ways:

  • A * may be used for either or both endpoints to specify an open-ended range query
    • field:[* TO 100] finds all field values less than or equal to 100
    • field:[100 TO *] finds all field values greater than or equal to 100
    • field:[* TO *] matches all documents with the field
  • Pure negative queries (all clauses prohibited) are allowed (only as a top-level clause)
    • -inStock:false finds all field values where inStock is not false
    • -field:[* TO *] finds all documents without a value for field
  • A hook into FunctionQuery syntax. You'll need to use quotes to encapsulate the function if it includes parentheses, as shown in the second example below:
    • _val_:myfield
    • _val_:"recip(rord(myfield),1,2,3)"
  • Support for using any type of query parser as a nested clause.
    • inStock:true OR {!dismax qf='name manu' v='ipod'}
  • Support for a special filter(...) syntax to indicate that some query clauses should be cached in the filter cache (as a constant score boolean query). This allows sub-queries to be cached and re-used in other queries. 
    For example inStock:true will be cached and re-used in all three of the queries below:
    • q=features:songs OR filter(inStock:true)
    • q=+manu:Apple +filter(inStock:true)
    • q=+manu:Apple & fq=inStock:true
    This can even be used to cache individual clauses of complex filter queries.  In the first query below, 3 items will be added to the filter cache (the top level fq and both filter(...) clauses) and in the second query, there will be 2 cache hits, and one new cache insertion (for the new top level fq):
    • q=features:songs & fq=+filter(inStock:true) +filter(price:[* TO 100])
    • q=manu:Apple & fq=-filter(inStock:true) -filter(price:[* TO 100])
  • Range queries ("[a TO z]"), prefix queries ("a*"), and wildcard queries ("a*b") are constant-scoring (all matching documents get an equal score). The scoring factors TF, IDF, index boost, and "coord" are not used. There is no limitation on the number of terms that match (as there was in past versions of Lucene).
  • Constant score queries are created with <query_clause>^=<score>, which sets the entire clause to the specified score for any documents matching that clause:
    • q=(description:blue color:blue)^=1.0 title:blue^=5.0

Specifying Dates and Times

Queries against fields using the TrieDateField type (typically range queries) should use the appropriate date syntax:

  • timestamp:[* TO NOW]
  • createdate:[1976-03-06T23:59:59.999Z TO *]
  • createdate:[1995-12-31T23:59:59.999Z TO 2007-03-06T00:00:00Z]
  • pubdate:[NOW-1YEAR/DAY TO NOW/DAY+1DAY]
  • createdate:[1976-03-06T23:59:59.999Z TO 1976-03-06T23:59:59.999Z+1YEAR]
  • createdate:[1976-03-06T23:59:59.999Z/YEAR TO 1976-03-06T23:59:59.999Z]

Related Topics

 

  • No labels

11 Comments

  1. At least in Solr 4.5, you can mix the two brackets for range searches.  For example:

    This will match the upper bound of 10, but will not match the lower bound of 1.  Is this a deliberate syntax feature, or merely an accident of the current implementation?  Either, the docs should probably mention it, either saying it's allowed or warning that it's unsupported.

  2. Andrew, it's definitely a fully supported syntax.  I don't think it worked in 3.x, but it does in 4.x.

    https://issues.apache.org/jira/browse/SOLR-355

    I will update this page shortly.

  3. This page could use some additional cleanup:

    • a lot of the historic info from the intro paragraph is really old and doesn't need to be included anymore – there is a lot of better "intro" info we could provide
    • we need more non trivial examples of mixing features
    • we need more details on how (multiple) nested queries (with their own local params) can be expressed and how the parsing rules work in terms of the stages of parsing and what pieces of a query string are passed to the nested parser.
  4. I believe that the first (and maybe the second) paragraph has an issue. The statement "the Standard Request Handler calls the DisMax query parser" should be "the Standard Request Handler calls the Lucene query parser". If "DisMax" is correct, then the second paragraph needs to be reworded, such that it does not indicate that DisMax is not the default query parser when it states that the standard query parser is less tolerant of syntax errors than the DisMax query parser.

    "The advantage of the standard query parser is that it enables users to specify very precise queries. The disadvantage is that it is less tolerant of syntax errors than the DisMax query parser. ..."

     

    1. yeah ... as mentioned in my previous comment, there's a lot of work that needs done on this page – but that intro was just atrocious so i ripped it out ... nothing would have almost been better then what we had before.

  5. How to implement sorting on the solr data?  I just want to sort data according to typed string and column priority. 

  6. Solr's xml result output doesn't add CDATA around string or text type. If the contents contains DBCS characters or some special character that may conflict with XML spec, it may produce problem. I always add CDATA when output string or text containing Chinese into XML-format and it always doesn't cause any parsing problem (Note: We have experinces when not add CDATA tag, xml parse will have error). I would suggest Solr add CDATA around string/text contents.

    1. scott, if you encounter non-valid XML output from Solr, please create a JIRA.  Defensive CDATA wrapping in all cases is a non-starter though.