fix(search): filter all special characters when searching

This commit is contained in:
LinkinStars 2023-10-08 15:11:02 +08:00
parent 79d025f0b1
commit 5101c12ec1
4 changed files with 20 additions and 2 deletions

View File

@ -422,7 +422,7 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er
ObjectID: answerID, ObjectID: answerID,
Title: question.Title, Title: question.Title,
Type: constant.AnswerObjectType, Type: constant.AnswerObjectType,
Content: answer.ParsedText, Content: answer.OriginalText,
Answers: 0, Answers: 0,
Status: plugin.SearchContentStatus(answer.Status), Status: plugin.SearchContentStatus(answer.Status),
Tags: tags, Tags: tags,

View File

@ -468,7 +468,7 @@ func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (er
ObjectID: questionID, ObjectID: questionID,
Title: question.Title, Title: question.Title,
Type: constant.QuestionObjectType, Type: constant.QuestionObjectType,
Content: question.ParsedText, Content: question.OriginalText,
Answers: int64(question.AnswerCount), Answers: int64(question.AnswerCount),
Status: plugin.SearchContentStatus(question.Status), Status: plugin.SearchContentStatus(question.Status),
Tags: tags, Tags: tags,

View File

@ -2,7 +2,10 @@ package schema
import ( import (
"github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/constant"
"github.com/answerdev/answer/internal/base/validator"
"github.com/answerdev/answer/plugin" "github.com/answerdev/answer/plugin"
"regexp"
"strings"
) )
type SearchDTO struct { type SearchDTO struct {
@ -15,6 +18,15 @@ type SearchDTO struct {
CaptchaCode string `json:"captcha_code"` 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 { type SearchCondition struct {
// search target type: all/question/answer // search target type: all/question/answer
TargetType string TargetType string

View File

@ -28,6 +28,12 @@ func (ss *SearchService) Search(ctx context.Context, dto *schema.SearchDTO) (res
if dto.Page < 1 { if dto.Page < 1 {
dto.Page = 1 dto.Page = 1
} }
if len(dto.Query) == 0 {
return &schema.SearchResp{
Total: 0,
SearchResults: make([]*schema.SearchResult, 0),
}, nil
}
// search type // search type
cond := ss.searchParser.ParseStructure(ctx, dto) cond := ss.searchParser.ParseStructure(ctx, dto)