-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add EscapeQueryChars utility function (#30)
- Loading branch information
1 parent
4372215
commit ae44b04
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package solr | ||
|
||
import ( | ||
"strings" | ||
"unicode" | ||
) | ||
|
||
// EscapeQueryChars escapes special characters in the given Solr query string that would normally be treated as part of | ||
// Solr's query syntax. For a full list of special characters, see the Solr documentation here: | ||
// https://solr.apache.org/guide/solr/9_7/query-guide/standard-query-parser.html#escaping-special-characters | ||
// | ||
// Returns the query string with special characters escaped | ||
func EscapeQueryChars(s string) string { | ||
var sb strings.Builder | ||
for _, c := range s { | ||
switch c { | ||
case '\\', '+', '-', '!', '(', ')', ':', '^', '[', ']', '"', '{', '}', '~', '*', '?', '|', '&', ';', '/': | ||
sb.WriteRune('\\') | ||
} | ||
if unicode.IsSpace(c) { | ||
sb.WriteRune('\\') | ||
} | ||
sb.WriteRune(c) | ||
} | ||
return sb.String() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package solr | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestEscapeQueryChars(t *testing.T) { | ||
a := assert.New(t) | ||
queryFromDocs := "(1+1):2" | ||
expected := `\(1\+1\)\:2` | ||
a.Equal(expected, EscapeQueryChars(queryFromDocs)) | ||
|
||
queryAllSpecialChars := `\+-!():^[]"{}~*?|&;/` | ||
expected2 := `\\\+\-\!\(\)\:\^\[\]\"\{\}\~\*\?\|\&\;\/` | ||
a.Equal(expected2, EscapeQueryChars(queryAllSpecialChars)) | ||
|
||
queryWhitespace := ` solr rocks` | ||
expected3 := `\ solr\ rocks` | ||
a.Equal(expected3, EscapeQueryChars(queryWhitespace)) | ||
} |