Van Tuan Tran
Van Tuan Tran

Reputation: 51

Search Exactly in Solr

Thanks for reading this question .

I am using Solr as Search Engine in my application.

When user searchs with "java design patterns". We want Solr returns documents contain exactly "java design patterns" and not "design patterns java" or "java patterns design"...Terms in document are indexed : "design", "patterns", "java" ... other terms.

How can I implement this ?.

Thanks,

Upvotes: 1

Views: 581

Answers (3)

Ahmed Salem
Ahmed Salem

Reputation: 1757

The trick is that spaces should replaces with\ to avoid it

Example: if we search with typeOfChange:*Cavity Ids* (it will not return anything) but if we use the pattern typeOfChange:*Cavity\ Ids* (it will return data)

What can help is:

ClientUtils.escapeQueryChars(value.toString())

And It's implementation:

 public static String escapeQueryChars(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      // These characters are part of the query syntax and must be escaped
      if (c == '\\' || c == '+' || c == '-' || c == '!'  || c == '(' || c == ')' || c == ':'
        || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
        || c == '*' || c == '?' || c == '|' || c == '&'  || c == ';' || c == '/'
        || Character.isWhitespace(c)) {
        sb.append('\\');
      }
      sb.append(c);
    }
    return sb.toString();
  }

Upvotes: 0

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can use PhraseQuery. Sending queries between double quotes will return you the exactly matched results.

There is also a question in the Solr FAQ page, which explains How to search one term near another.

Upvotes: 2

Jayendra
Jayendra

Reputation: 52779

You would need to check on SpanNearQuery which will help to set the terms to be in the same order as being search for.

A SpanNearQuery will look to find a number of SpanQuerys within a given distance from each other. You can specify that the spans must come in the order specified, or that order should not be considered. These SpanQuerys could be any number of TermQuerys, other SpanNearQuerys, or one of the other SpanQuerys mentioned below. You can nest arbitrarily, eg SpanNearQuerys can contain other SpanNearQuerys that contain still other SpanNearQuerys, etc.

There is a SurroundQueryParser which can help you create these queries, but its not been released yet.

You can create a new Parser by modifing the Dismax OR Edismax Parsers to Create the Span queries, instead of Phrase Queries, with 0 slop.

Upvotes: 2

Related Questions