feat:完成首页搜索功能

This commit is contained in:
henry
2022-01-18 16:29:29 +08:00
parent 478182dcb0
commit 10224e8db6
21 changed files with 572 additions and 167 deletions

View File

@ -79,7 +79,7 @@ func (c *Industry) Form(params *IndustryParams) error {
// Delete 删除操作
func (c *Industry) Delete(id uint64) error {
mSysIndustry := new(model.SysIndustry)
mSysIndustry := model.NewSysIndustry()
mSysIndustry.ID = id
isExist, err := model2.FirstField(mSysIndustry.SysIndustry, []string{"id"})

View File

@ -128,6 +128,8 @@ func (c *Demand) Form(params *DemandParams) error {
mTechnologyDemand.Name = params.Name
mTechnologyDemand.Mobile = params.Mobile
mTechnologyDemand.Introduce = params.Introduce
// TODO用户公司模式
mTechnologyDemand.Mode = params.Introduce
mTechnologyDemand.SetKindAttribute(params.Kinds)
mTechnologyDemand.SetIndustryAttribute(params.Industry)
mTechnologyDemand.Budget = params.Budget

View File

@ -23,19 +23,20 @@ func (*ES) Create(c *gin.Context) {
api.APIFailure(err.(error))(c)
return
}
//manage := service.NewESManage(
// service.WithManageID(form.ID),
// service.WithManageIdentity(form.Identity),
// service.WithManageTitle(form.Title),
// service.WithManageKeyword(form.Keyword),
// service.WithManageResearch(form.Research),
//)
manage := service.NewESPatent(
service.WithPatentID(form.ID),
//service.WithManageIdentity(form.Identity),
service.WithPatentTitle(form.Title),
service.WithPatentIndustry(form.Industry),
manage := service.NewESManage(
service.WithManageID(form.ID),
service.WithManageIdentity(form.Identity),
service.WithManageIndustry(form.Industry),
service.WithManageTitle(form.Title),
service.WithManageKeyword(form.Keyword),
service.WithManageResearch(form.Research),
)
//manage := service.NewESPatent(
// service.WithPatentID(form.ID),
// //service.WithManageIdentity(form.Identity),
// service.WithPatentTitle(form.Title),
// service.WithPatentIndustry(form.Industry),
//)
api.APIResponse(manage.Create())(c)
}
@ -49,16 +50,16 @@ func (*ES) Search(c *gin.Context) {
api.APIFailure(err.(error))(c)
return
}
//manage := service.NewESManage(service.WithManageIdentity(form.Identity),
// service.WithManageTitle(form.Param),
// service.WithManageIndustry(form.Industry),
// service.WithManageKeyword(form.Param),
// service.WithManageResearch(form.Param))
manage := service.NewESPatent(
service.WithPatentTitle(form.Param),
service.WithPatentIndustry(form.Industry),
)
data, err := manage.Search(1, 10)
manage := service.NewESManage(service.WithManageIdentity(form.Identity),
service.WithManageTitle(form.Param),
service.WithManageIndustry(form.Industry),
service.WithManageKeyword(form.Param),
service.WithManageResearch(form.Param))
//manage := service.NewESPatent(
// service.WithPatentTitle(form.Param),
// service.WithPatentIndustry(form.Industry),
//)
data, err := manage.Search(1, 10, nil)
for _, v := range data.([]interface{}) {
fmt.Println(reflect.TypeOf(v).String())

View File

@ -1,7 +1,7 @@
package api
import (
"SciencesServer/app/api/website/controller"
"SciencesServer/app/api/website/controller/search"
"SciencesServer/app/basic/api"
"github.com/gin-gonic/gin"
)
@ -10,15 +10,16 @@ type Search struct{}
func (*Search) Launch(c *gin.Context) {
form := &struct {
Mode int `json:"mode" form:"mode" binding:"required"`
Keyword string `json:"keyword" form:"keyword" binding:"required"`
Industry string `json:"industry" form:"industry"`
Mode int `json:"mode" form:"mode" binding:"required"`
Keyword string `json:"keyword" form:"keyword" binding:"required"`
Industry string `json:"industry" form:"industry"`
Params map[string]interface{} `json:"params" form:"params"`
api.PageForm
}{}
if err := api.Bind(form)(c); err != nil {
api.APIFailure(err.(error))(c)
return
}
data, err := controller.NewSearch()().Launch(form.Mode, form.Keyword, form.Industry, form.Page, form.PageSize)
data, err := search.NewInstance()().Launch(form.Mode, form.Keyword, form.Industry, form.Params, form.Page, form.PageSize)
api.APIResponse(err, data)(c)
}

View File

@ -57,7 +57,7 @@ func achievement(uids []uint64, page, pageSize int) (*controller.ReturnPages, er
var count int64
out, err := mTechnologyAchievement.Achievement(page, pageSize, &count, model2.NewWhereIn("uid", uids))
out, err := mTechnologyAchievement.Achievements(page, pageSize, &count, model2.NewWhereIn("uid", uids))
if err != nil {
return nil, err

View File

@ -1,59 +0,0 @@
package controller
import (
"SciencesServer/app/basic/config"
"SciencesServer/app/service"
"errors"
)
type Search struct{}
type SearchHandle func() *Search
var searchHandle = map[int]func(int, int, string, string) (interface{}, error){
1: searchCompany,
}
// searchCompany 公司搜索
func searchCompany(page, pageSize int, keyword, industry string) (interface{}, error) {
manage := service.NewESManage(
service.WithManageIdentity(config.TenantUserIdentityForCompany),
service.WithManageTitle(keyword),
service.WithManageKeyword(keyword),
service.WithManageResearch(keyword),
)
if industry != "" {
manage.Industry = industry
}
out, err := manage.Search(page, pageSize, nil)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESManage)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
return nil, nil
}
// Launch 发起搜索
func (c *Search) Launch(mode int, keyword, industry string, page, pageSize int) (interface{}, error) {
handle, has := searchHandle[mode]
if !has {
return nil, errors.New("操作错误,未知的搜索模式")
}
return handle(page, pageSize, keyword, industry)
}
func NewSearch() SearchHandle {
return func() *Search {
return &Search{}
}
}

View File

@ -0,0 +1,69 @@
package search
import (
"SciencesServer/app/api/website/model"
"SciencesServer/app/basic/config"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/service"
config2 "SciencesServer/config"
)
type (
AchievementInfo struct {
ID string `json:"id"`
*model.TechnologyAchievementInfo
Customers []string `json:"customers"`
Industrys []string `json:"industrys"`
Keywords []string `json:"keywords"`
}
)
func achievementSearch(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
manage := service.NewESAchievement(
service.WithAchievementTitle(keyword),
service.WithAchievementKeyword(keyword),
)
if industry != "" {
service.WithAchievementIndustry(keyword)(manage)
}
out, err := manage.Search(page, pageSize)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESAchievement)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
mTechnologyAchievement := model.NewTechnologyAchievement()
achievements := make([]*model.TechnologyAchievementInfo, 0)
if achievements, err = mTechnologyAchievement.Achievement(model2.NewWhereIn("a.id", ids)); err != nil {
return nil, err
}
list := make([]*AchievementInfo, 0)
for _, v := range achievements {
_industrys := make([]string, 0)
for _, v := range v.GetIndustryAttribute() {
_industrys = append(_industrys, config.GetIndustryInfo(v, "-", "/"))
}
v.Image.Image = v.Image.Analysis(config2.SystemConfig[config2.SysImageDomain])
list = append(list, &AchievementInfo{
ID: v.GetEncodeID(), TechnologyAchievementInfo: v,
Customers: v.GetCustomerAttribute(),
Industrys: _industrys, Keywords: v.GetKeywordAttribute(),
})
}
return list, nil
}

View File

@ -0,0 +1,72 @@
package search
import (
"SciencesServer/app/api/website/model"
"SciencesServer/app/basic/config"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/service"
config2 "SciencesServer/config"
)
type (
CompanyInfo struct {
ID string `json:"id"`
Kind model2.ManageCompanyKind `json:"kind"`
Name string `json:"name"`
Image string `json:"image"`
Product string `json:"product"`
Url string `json:"url"`
Industrys []string `json:"industrys"`
Keywords []string `json:"keywords"`
}
)
// searchCompany 公司搜索
func searchCompany(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
manage := service.NewESManage(
service.WithManageIdentity(config.TenantUserIdentityForCompany),
service.WithManageTitle(keyword),
service.WithManageKeyword(keyword),
service.WithManageResearch(keyword),
)
if industry != "" {
service.WithManageIndustry(industry)(manage)
}
out, err := manage.Search(page, pageSize, nil)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESManage)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
mManageCompany := model.NewManageCompany()
companys := make([]*model2.ManageCompany, 0)
if err = model2.ScanFields(mManageCompany.ManageCompany, &companys, []string{"id", "name", "kind", "image", "product",
"industry", "keyword", "url"}, &model2.ModelWhereOrder{Where: model2.NewWhereIn("id", ids)}); err != nil {
return nil, err
}
list := make([]*CompanyInfo, 0)
for _, v := range companys {
_industrys := make([]string, 0)
for _, v := range v.GetIndustryAttribute() {
_industrys = append(_industrys, config.GetIndustryInfo(v, "-", "/"))
}
list = append(list, &CompanyInfo{
ID: v.GetEncodeID(), Kind: v.Kind, Name: v.Name,
Image: v.Image.Analysis(config2.SystemConfig[config2.SysImageDomain]),
Product: v.Product, Industrys: _industrys, Keywords: v.GetKeywordAttribute(),
})
}
return list, nil
}

View File

@ -0,0 +1,74 @@
package search
import (
"SciencesServer/app/api/website/model"
model2 "SciencesServer/app/common/model"
"fmt"
"time"
)
type (
// DemandInfo 需求信息
DemandInfo struct {
ID string `json:"id"`
Title string `json:"title"`
Mode string `json:"mode"`
Kind string `json:"kind"`
Industrys []string `json:"industrys"`
Budget float64 `json:"budget"`
BudgetMode model2.TechnologyDemandBudgetMode `json:"budget_mode"`
Deadline time.Time `json:"deadline"`
}
)
// searchDemand 需求搜索
func searchDemand(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
mTechnologyDemand := model.NewTechnologyDemand()
out := make([]*model2.TechnologyDemand, 0)
where := []*model2.ModelWhereOrder{
&model2.ModelWhereOrder{
Where: model2.NewWhere("status", model2.TechnologyDemandStatusForAgree),
Order: model2.NewOrder("id", model2.OrderModeToDesc),
},
}
if keyword != "" {
where = append(where, &model2.ModelWhereOrder{
Where: model2.NewWhereLike("title", keyword),
})
}
if industry != "" {
where = append(where, &model2.ModelWhereOrder{Where: model2.NewWhereCondition("industry", "LIKE",
"%"+fmt.Sprintf(`"%v`, industry)+"%")})
}
if len(params) > 0 {
for k, v := range params {
where = append(where, &model2.ModelWhereOrder{
Where: model2.NewWhere(k, v),
})
}
}
var count int64
if err := model2.PagesFields(mTechnologyDemand.TechnologyDemand, &out, []string{"id", "title", "mode", "kind", "industry",
"budget", "budget_mode", "deadline"}, page, pageSize, &count, where...); err != nil {
return nil, err
}
list := make([]*DemandInfo, 0)
for _, v := range out {
list = append(list, &DemandInfo{
ID: v.GetEncodeID(), Title: v.Title,
Mode: v.Mode,
Kind: v.Kind,
Industrys: v.GetIndustryAttribute(),
Budget: v.Budget,
BudgetMode: v.BudgetMode,
Deadline: v.Deadline,
})
}
return list, nil
}

View File

@ -0,0 +1,70 @@
package search
import (
"SciencesServer/app/api/website/model"
"SciencesServer/app/basic/config"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/service"
config2 "SciencesServer/config"
)
type (
// ExpertInfo 专家信息
ExpertInfo struct {
ID string `json:"id"`
*model.ManageExpertInfo
Industrys []string `json:"industrys"`
Keywords []string `json:"keywords"`
}
)
// searchExpert 专家搜索
func searchExpert(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
manage := service.NewESManage(
service.WithManageIdentity(config.TenantUserIdentityForExpert),
service.WithManageTitle(keyword),
service.WithManageKeyword(keyword),
service.WithManageResearch(keyword),
)
if industry != "" {
service.WithManageIndustry(industry)(manage)
}
out, err := manage.Search(page, pageSize, nil)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESManage)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
mManageExpert := model.NewManageExpert()
experts := make([]*model.ManageExpertInfo, 0)
if experts, err = mManageExpert.Expert(3, model2.NewWhereIn("e.id", ids)); err != nil {
return nil, err
}
list := make([]*ExpertInfo, 0)
for _, v := range experts {
_industrys := make([]string, 0)
for _, v := range v.GetIndustryAttribute() {
_industrys = append(_industrys, config.GetIndustryInfo(v, "-", "/"))
}
v.Image.Image = v.Image.Analysis(config2.SystemConfig[config2.SysImageDomain])
list = append(list, &ExpertInfo{
ID: v.GetEncodeID(), ManageExpertInfo: v,
Industrys: _industrys, Keywords: v.GetKeywordAttribute(),
})
}
return list, nil
}

View File

@ -0,0 +1,30 @@
package search
import (
"errors"
)
type Instance struct{}
type InstanceHandle func() *Instance
var instanceHandle = map[int]func(int, int, string, string, map[string]interface{}) (interface{}, error){
1: searchCompany, 2: achievementSearch, 3: searchLaboratory,
4: searchPatent, 5: searchExpert, 6: searchDemand,
}
// Launch 发起搜索
func (c *Instance) Launch(mode int, keyword, industry string, params map[string]interface{}, page, pageSize int) (interface{}, error) {
handle, has := instanceHandle[mode]
if !has {
return nil, errors.New("操作错误,未知的搜索模式")
}
return handle(page, pageSize, keyword, industry, params)
}
func NewInstance() InstanceHandle {
return func() *Instance {
return &Instance{}
}
}

View File

@ -0,0 +1,70 @@
package search
import (
"SciencesServer/app/api/website/model"
"SciencesServer/app/basic/config"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/service"
config2 "SciencesServer/config"
)
type (
// LaboratoryInfo 实验室信息
LaboratoryInfo struct {
ID string `json:"id"`
*model.ManageLaboratoryInfo
Industrys []string `json:"industrys"`
Keywords []string `json:"keywords"`
}
)
// searchLaboratory 实验室搜索
func searchLaboratory(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
manage := service.NewESManage(
service.WithManageIdentity(config.TenantUserIdentityForLaboratory),
service.WithManageTitle(keyword),
service.WithManageKeyword(keyword),
service.WithManageResearch(keyword),
)
if industry != "" {
service.WithManageIndustry(industry)(manage)
}
out, err := manage.Search(page, pageSize, nil)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESAchievement)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
mManageLaboratory := model.NewManageLaboratory()
laboratorys := make([]*model.ManageLaboratoryInfo, 0)
if laboratorys, err = mManageLaboratory.Laboratory(model2.NewWhereIn("l.id", ids)); err != nil {
return nil, err
}
list := make([]*LaboratoryInfo, 0)
for _, v := range laboratorys {
_industrys := make([]string, 0)
for _, v := range v.GetIndustryAttribute() {
_industrys = append(_industrys, config.GetIndustryInfo(v, "-", "/"))
}
v.Image.Image = v.Image.Analysis(config2.SystemConfig[config2.SysImageDomain])
list = append(list, &LaboratoryInfo{
ID: v.GetEncodeID(), ManageLaboratoryInfo: v,
Industrys: _industrys, Keywords: v.GetKeywordAttribute(),
})
}
return list, nil
}

View File

@ -0,0 +1,59 @@
package search
import (
"SciencesServer/app/api/website/model"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/service"
)
type (
// PatentInfo 专利信息
PatentInfo struct {
ID string `json:"id"`
Kind model2.SysParentKind `json:"kind"`
Title string `json:"title"`
ApplyAt string `json:"apply_at"`
Description string `json:"description"`
}
)
// searchPatent 专利搜索
func searchPatent(page, pageSize int, keyword, industry string, params map[string]interface{}) (interface{}, error) {
manage := service.NewESPatent(
service.WithPatentTitle(keyword),
)
if industry != "" {
service.WithPatentIndustry(industry)(manage)
}
out, err := manage.Search(page, pageSize)
if err != nil {
return nil, err
}
ids := make([]uint64, 0)
for _, v := range out.([]interface{}) {
val := v.(*service.ESPatent)
ids = append(ids, val.ID)
}
if len(ids) <= 0 {
return nil, nil
}
mSysPatent := model.NewSysPatent()
patents := make([]*model2.SysPatent, 0)
if err = model2.ScanFields(mSysPatent.SysPatent, &patents, []string{"id", "kind", "title", "apply_at", "description"},
&model2.ModelWhereOrder{Where: model2.NewWhereIn("id", ids)}); err != nil {
return nil, err
}
list := make([]*PatentInfo, 0)
for _, v := range patents {
list = append(list, &PatentInfo{
ID: v.GetEncodeID(), Kind: v.Kind, Title: v.Title, ApplyAt: v.ApplyAt, Description: v.Description,
})
}
return list, nil
}

View File

@ -54,7 +54,7 @@ func (c *Achievement) Instance(title, industry string, page, pageSize int) (*con
}
var count int64
out, err := mTechnologyAchievement.Achievement(page, pageSize, &count, where...)
out, err := mTechnologyAchievement.Achievements(page, pageSize, &count, where...)
if err != nil {
return nil, err

View File

@ -57,7 +57,7 @@ func (c *Patent) Instance(title, industry string, page, pageSize int) (*controll
}
ret := make([]*model.SysPatentInfo, 0)
if ret, err = mSysPatent.Patent(page, pageSize, &count, model2.NewWhereIn("p.id", ids)); err != nil {
if ret, err = mSysPatent.Patents(page, pageSize, &count, model2.NewWhereIn("p.id", ids)); err != nil {
return nil, err
}
for _, v := range ret {

View File

@ -40,8 +40,8 @@ func (m *SysPatent) Instance(where ...*model.ModelWhere) ([]*SysPatentInfo, erro
return out, nil
}
// Patent 专利信息
func (m *SysPatent) Patent(page, pageSize int, count *int64, where ...*model.ModelWhere) ([]*SysPatentInfo, error) {
// Patents 专利信息
func (m *SysPatent) Patents(page, pageSize int, count *int64, where ...*model.ModelWhere) ([]*SysPatentInfo, error) {
db := orm.GetDB().Table(m.TableName()+" AS p").
Select("p.id", "p.title", "LEFT(p.description, 80) AS description", "p.apply_at").
Joins(fmt.Sprintf("LEFT JOIN %s AS c ON p.ipc_code = c.ipc AND c.is_deleted = %d",

View File

@ -17,8 +17,8 @@ type TechnologyAchievementInfo struct {
CollectCount int `json:"collect_count"`
}
// Achievement 成果信息
func (m *TechnologyAchievement) Achievement(page, pageSize int, count *int64, where ...*model.ModelWhere) ([]*TechnologyAchievementInfo, error) {
// Achievements 成果信息
func (m *TechnologyAchievement) Achievements(page, pageSize int, count *int64, where ...*model.ModelWhere) ([]*TechnologyAchievementInfo, error) {
db := orm.GetDB().Table(m.TableName()+" AS a").
Select("a.id", "a.title", "a.mode", "a.image", "a.charge_info", "a.industry", "a.customer", "a.maturity",
"a.cooperation_mode", "a.keyword", "v.count AS visit_count", "c.count AS collect_count").
@ -45,6 +45,32 @@ func (m *TechnologyAchievement) Achievement(page, pageSize int, count *int64, wh
return out, nil
}
// Achievement 成果信息
func (m *TechnologyAchievement) Achievement(where ...*model.ModelWhere) ([]*TechnologyAchievementInfo, error) {
db := orm.GetDB().Table(m.TableName()+" AS a").
Select("a.id", "a.title", "a.mode", "a.image", "a.charge_info", "a.industry", "a.customer", "a.maturity",
"a.cooperation_mode", "a.keyword", "v.count AS visit_count", "c.count AS collect_count").
Joins(fmt.Sprintf("LEFT JOIN (SELECT object_id, SUM(count) AS count FROM %s WHERE kind = %d AND is_deleted = %d GROUP BY object_id) AS v ON a.id = v.object_id",
model.NewUserVisit().TableName(), model.UserCollectKindForTechnologyAchievement, model.DeleteStatusForNot)).
Joins(fmt.Sprintf("LEFT JOIN (SELECT object_id, COUNT(id) AS count FROM %s WHERE kind = %d AND is_deleted = %d GROUP BY object_id) AS c ON a.id = c.object_id",
model.NewUserCollect().TableName(), model.UserCollectKindForTechnologyAchievement, model.DeleteStatusForNot)).
Where("a.status = ?", model.TechnologyAchievementStatusForAgree).
Where("a.is_deleted = ?", model.DeleteStatusForNot)
out := make([]*TechnologyAchievementInfo, 0)
if len(where) > 0 {
for _, v := range where {
db = db.Where(v.Condition, v.Value)
}
}
if err := db.Order("a.id " + model.OrderModeToDesc).Scan(&out).Error; err != nil {
return nil, err
}
return out, nil
}
// Detail 成果详细信息
func (m *TechnologyAchievement) Detail(id uint64) (*TechnologyAchievementInfo, error) {
db := orm.GetDB().Table(m.TableName()+" AS a").

View File

@ -12,7 +12,8 @@ type TechnologyDemand struct {
ModelTenant
UID uint64 `gorm:"column:uid;type:int;default:0;comment:用户uuid" json:"-"`
Title string `gorm:"column:title;type:varchar(50);default:'';comment:需求名称" json:"title"`
Kind string `gorm:"column:kind;type:varchar(50);default:'';comment:需求类别" json:"-"`
Mode string `gorm:"column:mode;type:varchar(50);default:'';comment:需求模式(普通企业需求)" json:"-"`
Kind string `gorm:"column:kind;type:varchar(100);default:'';comment:需求类别" json:"-"`
Name string `gorm:"column:name;type:varchar(30);default:'';comment:联系人" json:"name"`
Mobile string `gorm:"column:mobile;type:varchar(15);default:'';comment:联系方式" json:"mobile"`
Industry string `gorm:"column:industry;type:varchar(255);comment:所属领域;行业信息" json:"-"`

View File

@ -1,11 +1,11 @@
package es
import (
"SciencesServer/utils"
"context"
"encoding/json"
"fmt"
"github.com/olivere/elastic/v7"
"strings"
"testing"
)
@ -16,9 +16,9 @@ var (
)
type Student struct {
Name string `json:"name"`
Age int64 `json:"age"`
AverageScore float64 `json:"average_score"`
ID uint64 `json:"id"`
Name string `json:"name"`
Age int64 `json:"age"`
}
func _new() *elastic.Client {
@ -33,65 +33,49 @@ func _new() *elastic.Client {
return client
}
func TestNewInstance(t *testing.T) {
func TestNewInstanceCreate(t *testing.T) {
client := _new()
//client.Delete()
//newStudent := Student{
// Name: "熊,桥,顺",
// Age: 10,
// AverageScore: 99.9,
//}
//dataJSON, _ := json.Marshal(newStudent)
//
//_, err = client.Index().
// Index("students").
// BodyJson(string(dataJSON)).
// Do(context.Background())
//
//if err != nil {
// panic(err)
//}
var students []Student
searchSource := elastic.NewSearchSource()
searchSource.Query(elastic.NewMatchQuery("name", "顺"))
queryStr, _ := searchSource.Source()
queryJs, _ := json.Marshal(queryStr)
fmt.Println("[esclient]Final ESQuery=\n", string(queryJs))
searchService := client.Search().Index("students").SearchSource(searchSource)
searchResult, err1 := searchService.Do(context.Background())
if err1 != nil {
fmt.Println("[ProductsES][GetPIds]Error=", err1)
return
}
for _, hit := range searchResult.Hits.Hits {
var student Student
err := json.Unmarshal(hit.Source, &student)
if err != nil {
fmt.Println("[Getting Students][Unmarshal] Err=", err)
}
students = append(students, student)
}
t.Log(students)
src := Student{ID: 2, Name: "henry", Age: 28}
client.Index().Index("student").Id(fmt.Sprintf("%d", src.ID)).BodyJson(utils.AnyToJSON(src)).
Do(context.Background())
}
func TestNewInstance1(t *testing.T) {
NewInstance(
WithEsAddress([]string{"http://192.168.0.188:9200"}),
).Init().Local()
var b strings.Builder
b.WriteString(`{"title" : "`)
b.WriteString("我是好人")
b.WriteString(`"}`)
//resp, err := client.Create(dataIndex, "2", strings.NewReader(b.String()))
//t.Log(err)
//t.Log(resp)
func TestNewInstanceUpdate(t *testing.T) {
client := _new()
//client.Delete()
src := &Student{ID: 1, Name: "Henry", Age: 28}
_, err := client.Update().Index("student").Id(fmt.Sprintf("%d", src.ID)).Doc(map[string]interface{}{
"age": 29,
}).Do(context.Background())
t.Log(err)
}
func TestNewInstanceSearch(t *testing.T) {
client := _new()
//client.Delete()
query := elastic.NewBoolQuery()
//query.Must(elastic.NewMatchQuery("age", "27"))
service := client.Search().Index("student")
result, err := service.Pretty(true).Query(query).Do(context.Background())
t.Log(err)
t.Log(utils.AnyToJSON(result))
src := new(Student)
for _, hit := range result.Hits.Hits {
if err = json.Unmarshal(hit.Source, src); err != nil {
t.Log(err)
return
}
fmt.Println(utils.AnyToJSON(src))
}
}
func TestNewInstance2(t *testing.T) {

View File

@ -73,21 +73,21 @@ func Search(src interface{}, index string, params *SearchParams, page, pageSize
}
out := make([]interface{}, 0)
_type := reflect.TypeOf(src)
_type := reflect.TypeOf(src).Elem()
for _, hit := range result.Hits.Hits {
data := reflect.New(_type).Interface()
_src := reflect.New(_type).Interface()
if err = json.Unmarshal(hit.Source, data); err != nil {
if err = json.Unmarshal(hit.Source, _src); err != nil {
return nil, err
}
out = append(out, data)
out = append(out, _src)
}
return out, err
}
// Delete 删除操作
func Delete(index string) error {
_, err := client.DeleteIndex(index).Do(context.Background())
func Delete(index, id string) error {
_, err := client.Delete().Index(index).Do(context.Background())
return err
}

View File

@ -40,14 +40,19 @@ func TestExchange(t *testing.T) {
}
func TestAnyToByte(t *testing.T) {
src := []int{1}
mark := 0
for i := 0; i < len(src); i++ {
mark = mark | src[i]
swan := func(a, b interface{}) {
// t world
c := b
b = a
a = c
t.Log(AnyToJSON(a))
t.Log(AnyToJSON(b))
t.Log(AnyToJSON(c))
}
t.Log(mark)
a := "hello"
b := "world"
swan(&a, &b)
}
func TestFromJSONFile(t *testing.T) {