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.

fix(search): filter all special characters when searching

LinkinStars5101c12ec13b
diff --git a/internal/repo/answer/answer_repo.go b/internal/repo/answer/answer_repo.go
index 31092477..18ae72f7 100644
--- a/internal/repo/answer/answer_repo.go
+++ b/internal/repo/answer/answer_repo.go
@@ -422,7 +422,7 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er
ObjectID: answerID,
Title: question.Title,
Type: constant.AnswerObjectType,
- Content: answer.ParsedText,
+ Content: answer.OriginalText,
Answers: 0,
Status: plugin.SearchContentStatus(answer.Status),
Tags: tags,
diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.go
index 966541e4..59b187d6 100644
--- a/internal/repo/question/question_repo.go
+++ b/internal/repo/question/question_repo.go
@@ -468,7 +468,7 @@ func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (er
ObjectID: questionID,
Title: question.Title,
Type: constant.QuestionObjectType,
- Content: question.ParsedText,
+ Content: question.OriginalText,
Answers: int64(question.AnswerCount),
Status: plugin.SearchContentStatus(question.Status),
Tags: tags,
diff --git a/internal/schema/search_schema.go b/internal/schema/search_schema.go
index e30e6997..e1cb0bf2 100644
--- a/internal/schema/search_schema.go
+++ b/internal/schema/search_schema.go
@@ -2,7 +2,10 @@ package schema
import (
"github.com/answerdev/answer/internal/base/constant"
+ "github.com/answerdev/answer/internal/base/validator"
"github.com/answerdev/answer/plugin"
+ "regexp"
+ "strings"
)
type SearchDTO struct {
@@ -15,6 +18,15 @@ type SearchDTO struct {
CaptchaCode string `json:"captcha_code"`
}
+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)
+ return nil, nil
+}
+
type SearchCondition struct {
// search target type: all/question/answer
TargetType string
diff --git a/internal/service/search_service.go b/internal/service/search_service.go
index d4f74e92..f89bd9cd 100644
--- a/internal/service/search_service.go
+++ b/internal/service/search_service.go
@@ -28,6 +28,12 @@ func (ss *SearchService) Search(ctx context.Context, dto *schema.SearchDTO) (res
if dto.Page < 1 {
dto.Page = 1
}
+ if len(dto.Query) == 0 {
+ return &schema.SearchResp{
+ Total: 0,
+ SearchResults: make([]*schema.SearchResult, 0),
+ }, nil
+ }
// search type
cond := ss.searchParser.ParseStructure(ctx, dto)