Skip to content

Commit ae44b04

Browse files
authored
Add EscapeQueryChars utility function (#30)
1 parent 4372215 commit ae44b04

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

utils.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package solr
2+
3+
import (
4+
"strings"
5+
"unicode"
6+
)
7+
8+
// EscapeQueryChars escapes special characters in the given Solr query string that would normally be treated as part of
9+
// Solr's query syntax. For a full list of special characters, see the Solr documentation here:
10+
// https://solr.apache.org/guide/solr/9_7/query-guide/standard-query-parser.html#escaping-special-characters
11+
//
12+
// Returns the query string with special characters escaped
13+
func EscapeQueryChars(s string) string {
14+
var sb strings.Builder
15+
for _, c := range s {
16+
switch c {
17+
case '\\', '+', '-', '!', '(', ')', ':', '^', '[', ']', '"', '{', '}', '~', '*', '?', '|', '&', ';', '/':
18+
sb.WriteRune('\\')
19+
}
20+
if unicode.IsSpace(c) {
21+
sb.WriteRune('\\')
22+
}
23+
sb.WriteRune(c)
24+
}
25+
return sb.String()
26+
}

utils_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package solr
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestEscapeQueryChars(t *testing.T) {
10+
a := assert.New(t)
11+
queryFromDocs := "(1+1):2"
12+
expected := `\(1\+1\)\:2`
13+
a.Equal(expected, EscapeQueryChars(queryFromDocs))
14+
15+
queryAllSpecialChars := `\+-!():^[]"{}~*?|&;/`
16+
expected2 := `\\\+\-\!\(\)\:\^\[\]\"\{\}\~\*\?\|\&\;\/`
17+
a.Equal(expected2, EscapeQueryChars(queryAllSpecialChars))
18+
19+
queryWhitespace := ` solr rocks`
20+
expected3 := `\ solr\ rocks`
21+
a.Equal(expected3, EscapeQueryChars(queryWhitespace))
22+
}

0 commit comments

Comments
 (0)