Skip to content

Commit

Permalink
Add EscapeQueryChars utility function (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
takanuva15 authored Feb 17, 2025
1 parent 4372215 commit ae44b04
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
26 changes: 26 additions & 0 deletions utils.go
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()
}
22 changes: 22 additions & 0 deletions utils_test.go
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))
}

0 comments on commit ae44b04

Please sign in to comment.