Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

update

hgaol1934ddbe2724
diff --git a/internal/schema/search_schema.go b/internal/schema/search_schema.go
index 786fb9bb..59f32c5e 100644
--- a/internal/schema/search_schema.go
+++ b/internal/schema/search_schema.go
@@ -41,12 +41,34 @@ type SearchDTO struct {
func (s *SearchDTO) Check() (errField []*validator.FormErrorField, err error) {
// Replace special characters.
// Special characters will cause the search abnormal, such as search for "#" will get nearly all the content that Markdown format.
- s.Query = regexp.MustCompile(`[+#.<>_()*]`).ReplaceAllString(s.Query, " ")
- s.Query = regexp.MustCompile(`\s+`).ReplaceAllString(s.Query, " ")
- s.Query = strings.TrimSpace(s.Query)
+ replacedContent, patterns := ReplaceSearchContent(s.Query)
+ s.Query = strings.Join(append(patterns, replacedContent), " ")
+
return nil, nil
}
+func ReplaceSearchContent(content string) (string, []string) {
+ // Define the regular expressions for key:value pairs and [tag]
+ keyValueRegex := regexp.MustCompile(`\w+:\S+`)
+ tagRegex := regexp.MustCompile(`\[\w+\]`)
+ // Define the pattern for characters to replace
+ replaceCharsPattern := regexp.MustCompile(`[+#.<>\-_()*]`)
+
+ // Extract key:value pairs
+ keyValues := keyValueRegex.FindAllString(content, -1)
+ // Extract [tag]
+ tags := tagRegex.FindAllString(content, -1)
+
+ // Replace key:value pairs and [tag] with empty string
+ contentWithoutPatterns := keyValueRegex.ReplaceAllString(content, "")
+ contentWithoutPatterns = tagRegex.ReplaceAllString(contentWithoutPatterns, "")
+
+ // Replace characters with pattern [+#.<>_()*] with space
+ replacedContent := replaceCharsPattern.ReplaceAllString(contentWithoutPatterns, " ")
+
+ return strings.TrimSpace(replacedContent), append(keyValues, tags...)
+}
+
type SearchCondition struct {
// search target type: all/question/answer
TargetType string
diff --git a/internal/schema/search_schema_test.go b/internal/schema/search_schema_test.go
new file mode 100644
index 00000000..1549f0e1
--- /dev/null
+++ b/internal/schema/search_schema_test.go
@@ -0,0 +1,22 @@
+package schema
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestReplaceSearchContent(t *testing.T) {
+ content := "user:aaa [tag] ssssfdfdf-as#fsadf"
+ replacedContent, patterns := ReplaceSearchContent(content)
+ ret := strings.Join(append(patterns, replacedContent), " ")
+
+ assert.Equal(t, "user:aaa [tag]ssssfdfdf as fsadf", ret)
+
+ content = "user:aaa-sss [tag1] ssssfdfdf-as#fsadf [tag2] score:3"
+ replacedContent, patterns = ReplaceSearchContent(content)
+ ret = strings.Join(append(patterns, replacedContent), " ")
+
+ assert.Equal(t, "user:aaa-sss score:3 [tag1] [tag2] ssssfdfdf as fsadf", ret)
+}