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): fix search condition

LinkinStars6f812a0a56ca
diff --git a/internal/controller/search_controller.go b/internal/controller/search_controller.go
index 5b658351..f0e18919 100644
--- a/internal/controller/search_controller.go
+++ b/internal/controller/search_controller.go
@@ -36,11 +36,10 @@ func (sc *SearchController) Search(ctx *gin.Context) {
}
dto.UserID = middleware.GetLoginUserIDFromContext(ctx)
- resp, total, extra, err := sc.searchService.Search(ctx, &dto)
+ resp, total, err := sc.searchService.Search(ctx, &dto)
handler.HandleResponse(ctx, err, schema.SearchListResp{
Total: total,
SearchResp: resp,
- Extra: extra,
})
}
diff --git a/internal/repo/answer/answer_repo.go b/internal/repo/answer/answer_repo.go
index 48a3166d..f6a2ff1a 100644
--- a/internal/repo/answer/answer_repo.go
+++ b/internal/repo/answer/answer_repo.go
@@ -3,7 +3,6 @@ package answer
import (
"context"
"github.com/answerdev/answer/plugin"
- "strings"
"time"
"github.com/answerdev/answer/internal/base/constant"
@@ -353,7 +352,7 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er
var (
question *entity.Question
)
- exist, err = ar.data.DB.Where("id = ?", answer.QuestionID).Get(&question)
+ exist, err = ar.data.DB.Context(ctx).Where("id = ?", answer.QuestionID).Get(&question)
if err != nil {
err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()
}
@@ -366,7 +365,7 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er
tagListList = make([]*entity.TagRel, 0)
tags = make([]string, 0)
)
- st := ar.data.DB.Where("object_id = ?", uid.DeShortID(question.ID))
+ st := ar.data.DB.Context(ctx).Where("object_id = ?", uid.DeShortID(question.ID))
st.Where("status = ?", entity.TagRelStatusAvailable)
err = st.Find(&tagListList)
if err != nil {
@@ -379,12 +378,12 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er
content := &plugin.SearchContent{
ObjectID: answerID,
Title: question.Title,
- Type: "question",
+ Type: constant.AnswerObjectType,
Content: answer.ParsedText,
Answers: 0,
Status: int64(answer.Status),
Tags: tags,
- QuesionID: answerID,
+ QuestionID: answer.QuestionID,
UserID: answer.UserID,
Views: int64(question.ViewCount),
Created: answer.CreatedAt.Unix(),
diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.go
index aa0dd3a2..19324eb4 100644
--- a/internal/repo/question/question_repo.go
+++ b/internal/repo/question/question_repo.go
@@ -4,8 +4,8 @@ import (
"context"
"encoding/json"
"fmt"
- "github.com/segmentfault/pacman/log"
"github.com/answerdev/answer/plugin"
+ "github.com/segmentfault/pacman/log"
"strings"
"time"
"unicode"
@@ -419,11 +419,8 @@ func (qr *questionRepo) AdminQuestionPage(ctx context.Context, search *schema.Ad
// updateSearch update search, if search plugin not enable, do nothing
func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (err error) {
- questionID = uid.DeShortID(questionID)
// check search plugin
- var (
- s plugin.Search
- )
+ var s plugin.Search
_ = plugin.CallSearch(func(search plugin.Search) error {
s = search
return nil
@@ -431,6 +428,7 @@ func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (er
if s == nil {
return
}
+ questionID = uid.DeShortID(questionID)
question, exist, err := qr.GetQuestion(ctx, questionID)
if !exist {
return
@@ -444,11 +442,11 @@ func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (er
tagListList = make([]*entity.TagRel, 0)
tags = make([]string, 0)
)
- session := qr.data.DB.Where("object_id = ?", questionID)
+ session := qr.data.DB.Context(ctx).Where("object_id = ?", questionID)
session.Where("status = ?", entity.TagRelStatusAvailable)
err = session.Find(&tagListList)
if err != nil {
- err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()
+ return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()
}
for _, tag := range tagListList {
tags = append(tags, tag.TagID)
@@ -456,12 +454,12 @@ func (qr *questionRepo) updateSearch(ctx context.Context, questionID string) (er
content := &plugin.SearchContent{
ObjectID: questionID,
Title: question.Title,
- Type: "question",
+ Type: constant.QuestionObjectType,
Content: question.ParsedText,
Answers: int64(question.AnswerCount),
Status: int64(question.Status),
Tags: tags,
- QuesionID: questionID,
+ QuestionID: questionID,
UserID: question.UserID,
Views: int64(question.ViewCount),
Created: question.CreatedAt.Unix(),
diff --git a/internal/repo/search_common/search_repo.go b/internal/repo/search_common/search_repo.go
index 1674698e..ca659991 100644
--- a/internal/repo/search_common/search_repo.go
+++ b/internal/repo/search_common/search_repo.go
@@ -445,7 +445,7 @@ func (sr *searchRepo) ParseSearchPluginResult(ctx context.Context, sres []plugin
And(builder.Lt{"`question`.`status`": entity.QuestionStatusDeleted}).
And(builder.Lt{"`answer`.`status`": entity.AnswerStatusDeleted}).And(builder.Eq{"`question`.`show`": entity.QuestionShow})
}
- qres, err = sr.data.DB.Query(b)
+ qres, err = sr.data.DB.Context(ctx).Query(b)
if err != nil || len(qres) == 0 {
continue
}
diff --git a/internal/schema/search_schema.go b/internal/schema/search_schema.go
index 51ec0f6a..0f2e0f56 100644
--- a/internal/schema/search_schema.go
+++ b/internal/schema/search_schema.go
@@ -1,5 +1,7 @@
package schema
+import "github.com/answerdev/answer/internal/base/constant"
+
type SearchDTO struct {
UserID string // UserID current login user ID
Query string `validate:"required,gte=1,lte=60" json:"q" form:"q"` // Query the query string
@@ -8,6 +10,44 @@ type SearchDTO struct {
Order string `validate:"required,oneof=newest active score relevance" form:"order,default=relevance" json:"order" enums:"newest,active,score,relevance"`
}
+type SearchCondition struct {
+ // search target type: all/question/answer
+ TargetType string
+ // search query user id
+ UserID string
+ // vote amount
+ VoteAmount int
+ // only show not accepted answer's question
+ NotAccepted bool
+ // view amount
+ Views int
+ // answer count
+ AnswerAmount int
+ // only show accepted answer
+ Accepted bool
+ // only show this question's answer
+ QuestionID string
+ // search query tags
+ Tags []string
+ // search query keywords
+ Words []string
+}
+
+// SearchAll check if search all
+func (s *SearchCondition) SearchAll() bool {
+ return len(s.TargetType) == 0
+}
+
+// SearchQuestion check if search only need question
+func (s *SearchCondition) SearchQuestion() bool {
+ return s.TargetType == constant.QuestionObjectType
+}
+
+// SearchAnswer check if search only need answer
+func (s *SearchCondition) SearchAnswer() bool {
+ return s.TargetType == constant.AnswerObjectType
+}
+
type SearchObject struct {
ID string `json:"id"`
QuestionID string `json:"question_id"`
diff --git a/internal/service/search_parser/search_parser.go b/internal/service/search_parser/search_parser.go
index ec56679f..bbbbf2dd 100644
--- a/internal/service/search_parser/search_parser.go
+++ b/internal/service/search_parser/search_parser.go
@@ -2,6 +2,7 @@ package search_parser
import (
"context"
+ "github.com/answerdev/answer/internal/base/constant"
"regexp"
"strings"
@@ -25,141 +26,66 @@ func NewSearchParser(tagCommonService *tag_common.TagCommonService, userCommon *
// ParseStructure parse search structure, maybe match one of type all/questions/answers,
// but if match two type, it will return false
-func (sp *SearchParser) ParseStructure(dto *schema.SearchDTO) (
- searchType string,
- // search all
- userID string,
- votes int,
- // search questions
- notAccepted bool,
- isQuestion bool,
- views,
- answers int,
- // search answers
- accepted bool,
- questionID string,
- isAnswer bool,
- // common fields
- tags,
- words []string,
-) {
+func (sp *SearchParser) ParseStructure(ctx context.Context, dto *schema.SearchDTO) (cond *schema.SearchCondition) {
+ cond = &schema.SearchCondition{}
var (
- query = dto.Query
- currentUserID = dto.UserID
- all = 0
- q = 0
- a = 0
- withWords []string
- limitWords = 5
+ query = dto.Query
+ limitWords = 5
)
// match tags
- tags = sp.parseTags(&query)
+ cond.Tags = sp.parseTags(ctx, &query)
// match all
- userID = sp.parseUserID(&query, currentUserID)
- if userID != "" {
- searchType = "all"
- all = 1
- }
- votes = sp.parseVotes(&query)
- if votes != -1 {
- searchType = "all"
- all = 1
- }
- withWords = sp.parseWithin(&query)
- if len(withWords) > 0 {
- searchType = "all"
- all = 1
- }
+ cond.UserID = sp.parseUserID(ctx, &query, dto.UserID)
+ cond.VoteAmount = sp.parseVotes(&query)
+ cond.Words = sp.parseWithin(&query)
// match questions
- notAccepted = sp.parseNotAccepted(&query)
- if notAccepted {
- searchType = "question"
- q = 1
- }
- isQuestion = sp.parseIsQuestion(&query)
- if isQuestion {
- searchType = "question"
- q = 1
+ cond.NotAccepted = sp.parseNotAccepted(&query)
+ if cond.NotAccepted {
+ cond.TargetType = constant.QuestionObjectType
}
- views = sp.parseViews(&query)
- if views != -1 {
- searchType = "question"
- q = 1
+ cond.Views = sp.parseViews(&query)
+ if cond.Views != -1 {
+ cond.TargetType = constant.QuestionObjectType
}
- answers = sp.parseAnswers(&query)
- if answers != -1 {
- searchType = "question"
- q = 1
+ cond.AnswerAmount = sp.parseAnswers(&query)
+ if cond.AnswerAmount != -1 {
+ cond.TargetType = constant.QuestionObjectType
}
// match answers
- accepted = sp.parseAccepted(&query)
- if accepted {
- searchType = "answer"
- a = 1
- }
- questionID = sp.parseQuestionID(&query)
- if questionID != "" {
- searchType = "answer"
- a = 1
- }
- isAnswer = sp.parseIsAnswer(&query)
- if isAnswer {
- searchType = "answer"
- a = 1
- }
-
- if len(strings.TrimSpace(query)) > 0 {
- words = strings.Split(strings.TrimSpace(query), " ")
- } else {
- words = []string{}
+ cond.Accepted = sp.parseAccepted(&query)
+ if cond.Accepted {
+ cond.TargetType = constant.AnswerObjectType
}
-
- if len(withWords) > 0 {
- words = append(withWords, words...)
+ cond.QuestionID = sp.parseQuestionID(&query)
+ if cond.QuestionID != "" {
+ cond.TargetType = constant.AnswerObjectType
}
- // check limit words
- if len(words) > limitWords {
- words = words[:limitWords]
+ if sp.parseIsQuestion(&query) {
+ cond.TargetType = constant.QuestionObjectType
}
-
- // check tags' search is all or question
- if len(tags) > 0 {
- if len(words) > 0 {
- searchType = "all"
- all = 1
- } else if isAnswer {
- searchType = "answer"
- a = 1
- all = 0
- q = 0
- } else {
- searchType = "question"
- q = 1
- all = 0
- a = 0
- }
+ if sp.parseIsAnswer(&query) {
+ cond.TargetType = constant.AnswerObjectType
}
- // check match types greater than 1
- if all+q+a > 1 {
- searchType = ""
+ if len(strings.TrimSpace(query)) > 0 {
+ words := strings.Split(strings.TrimSpace(query), " ")
+ cond.Words = append(cond.Words, words...)
}
- // check not match
- if all+q+a == 0 && len(words) > 0 {
- searchType = "all"
+ // check limit words
+ if len(cond.Words) > limitWords {
+ cond.Words = cond.Words[:limitWords]
}
-
return
}
// parseTags parse search tags, return tag ids array
-func (sp *SearchParser) parseTags(query *string) (tags []string) {
+func (sp *SearchParser) parseTags(ctx context.Context, query *string) (tags []string) {
var (
// expire tag pattern
exprTag = `(?m)\[([a-zA-Z0-9-\+\.#]+)\]{1}?`
@@ -175,7 +101,7 @@ func (sp *SearchParser) parseTags(query *string) (tags []string) {
tags = []string{}
for _, item := range res {
- tag, exists, err := sp.tagCommonService.GetTagBySlugName(context.TODO(), item[1])
+ tag, exists, err := sp.tagCommonService.GetTagBySlugName(ctx, item[1])
if err != nil || !exists {
continue
}
@@ -193,7 +119,7 @@ func (sp *SearchParser) parseTags(query *string) (tags []string) {
}
// parseUserID return user id or current login user id
-func (sp *SearchParser) parseUserID(query *string, currentUserID string) (userID string) {
+func (sp *SearchParser) parseUserID(ctx context.Context, query *string, currentUserID string) (userID string) {
var (
exprUserID = `(?m)^user:([a-z0-9._-]+)`
exprMe = "user:me"
@@ -207,7 +133,7 @@ func (sp *SearchParser) parseUserID(query *string, currentUserID string) (userID
q = strings.ReplaceAll(q, exprMe, "")
} else if len(res) == 2 {
name := res[1]
- user, has, err := sp.userCommon.GetUserBasicInfoByUserName(context.TODO(), name)
+ user, has, err := sp.userCommon.GetUserBasicInfoByUserName(ctx, name)
if err == nil && has {
userID = user.ID
q = re.ReplaceAllString(q, "")
diff --git a/internal/service/search_service.go b/internal/service/search_service.go
index 87e6b1eb..9e9bff1b 100644
--- a/internal/service/search_service.go
+++ b/internal/service/search_service.go
@@ -24,35 +24,16 @@ func NewSearchService(
}
// Search search contents
-func (ss *SearchService) Search(ctx context.Context, dto *schema.SearchDTO) (resp []schema.SearchResp, total int64, extra interface{}, err error) {
- extra = nil
+func (ss *SearchService) Search(ctx context.Context, dto *schema.SearchDTO) (resp []schema.SearchResp, total int64, err error) {
if dto.Page < 1 {
dto.Page = 1
}
// search type
- searchType,
- // search all
- userID,
- votes,
- // search questions
- notAccepted,
- _,
- views,
- answers,
- // search answers
- accepted,
- questionID,
- _,
- // common fields
- tags,
- words := ss.searchParser.ParseStructure(dto)
+ cond := ss.searchParser.ParseStructure(ctx, dto)
// check search plugin
- var (
- s plugin.Search
- sres []plugin.SearchResult
- )
+ var s plugin.Search
_ = plugin.CallSearch(func(search plugin.Search) error {
s = search
return nil
@@ -60,37 +41,31 @@ func (ss *SearchService) Search(ctx context.Context, dto *schema.SearchDTO) (res
// search plugin is not found, call system search
if s == nil {
- switch searchType {
- case "all":
- resp, total, err = ss.searchRepo.SearchContents(ctx, words, tags, userID, votes, dto.Page, dto.Size, dto.Order)
- if err != nil {
- return nil, 0, nil, err
- }
- case "question":
- resp, total, err = ss.searchRepo.SearchQuestions(ctx, words, tags, notAccepted, views, answers, dto.Page, dto.Size, dto.Order)
- case "answer":
- resp, total, err = ss.searchRepo.SearchAnswers(ctx, words, tags, accepted, questionID, dto.Page, dto.Size, dto.Order)
+ if cond.SearchAll() {
+ resp, total, err = ss.searchRepo.SearchContents(ctx, cond.Words, cond.Tags, cond.UserID, cond.VoteAmount, dto.Page, dto.Size, dto.Order)
+ } else if cond.SearchQuestion() {
+ resp, total, err = ss.searchRepo.SearchQuestions(ctx, cond.Words, cond.Tags, cond.NotAccepted, cond.Views, cond.AnswerAmount, dto.Page, dto.Size, dto.Order)
+ } else if cond.SearchAnswer() {
+ resp, total, err = ss.searchRepo.SearchAnswers(ctx, cond.Words, cond.Tags, cond.Accepted, cond.QuestionID, dto.Page, dto.Size, dto.Order)
}
return
}
+ return ss.searchByPlugin(ctx, s, cond, dto)
+}
- // call search plugin
- switch searchType {
- case "all":
- sres, total, err = s.SearchContents(ctx, words, tags, userID, votes, dto.Page, dto.Size, dto.Order)
- case "question":
- sres, total, err = s.SearchQuestions(ctx, words, tags, notAccepted, views, answers, dto.Page, dto.Size, dto.Order)
- case "answer":
- sres, total, err = s.SearchAnswers(ctx, words, tags, accepted, questionID, dto.Page, dto.Size, dto.Order)
- }
- if err != nil || len(sres) == 0 {
- return nil, 0, nil, err
+func (ss *SearchService) searchByPlugin(ctx context.Context, finder plugin.Search, cond *schema.SearchCondition, dto *schema.SearchDTO) (resp []schema.SearchResp, total int64, err error) {
+ var res []plugin.SearchResult
+ if cond.SearchAll() {
+ res, total, err = finder.SearchContents(ctx, cond.Words, cond.Tags, cond.UserID, cond.VoteAmount, dto.Page, dto.Size, dto.Order)
+ } else if cond.SearchQuestion() {
+ res, total, err = finder.SearchQuestions(ctx, cond.Words, cond.Tags, cond.NotAccepted, cond.Views, cond.AnswerAmount, dto.Page, dto.Size, dto.Order)
+ } else if cond.SearchAnswer() {
+ res, total, err = finder.SearchAnswers(ctx, cond.Words, cond.Tags, cond.Accepted, cond.QuestionID, dto.Page, dto.Size, dto.Order)
}
- // parse search plugin result
- resp, err = ss.searchRepo.ParseSearchPluginResult(ctx, sres)
+ resp, err = ss.searchRepo.ParseSearchPluginResult(ctx, res)
if err != nil {
- return nil, 0, nil, err
+ return nil, 0, err
}
return
}
diff --git a/plugin/search.go b/plugin/search.go
index ccea025b..b81543e7 100644
--- a/plugin/search.go
+++ b/plugin/search.go
@@ -19,7 +19,7 @@ type SearchContent struct {
Answers int64 `json:"answers"`
Status int64 `json:"status"`
Tags []string `json:"tags"`
- QuesionID string `json:"questionID"`
+ QuestionID string `json:"questionID"`
UserID string `json:"userID"`
Views int64 `json:"views"`
Created int64 `json:"created"`