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.goindex 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 erObjectID: 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.goindex 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) (erObjectID: 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.goindex e30e6997..e1cb0bf2 100644--- a/internal/schema/search_schema.go+++ b/internal/schema/search_schema.go@@ -2,7 +2,10 @@ package schemaimport ("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/answerTargetType stringdiff --git a/internal/service/search_service.go b/internal/service/search_service.goindex 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) (resif dto.Page < 1 {dto.Page = 1}+ if len(dto.Query) == 0 {+ return &schema.SearchResp{+ Total: 0,+ SearchResults: make([]*schema.SearchResult, 0),+ }, nil+ }// search typecond := ss.searchParser.ParseStructure(ctx, dto)