elasticsearch.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/PuerkitoBio/goquery"
  7. "github.com/olivere/elastic/v7"
  8. "github.com/olivere/elastic/v7/config"
  9. "hongze/hongze_cygx/models"
  10. "hongze/hongze_cygx/utils"
  11. "html"
  12. "log"
  13. "os"
  14. "strconv"
  15. "strings"
  16. )
  17. const (
  18. ES_URL = "http://es-cn-nif227b580019rgw6.public.elasticsearch.aliyuncs.com:9200" //<1>
  19. ES_USERNAME = "elastic" //<2>
  20. ES_PASSWORD = "hongze@2021" //<3>
  21. //Grafana pwd-> 20521bb9
  22. //Grafana username-> emon
  23. )
  24. func SaveData() {
  25. //fmt.Println("start")
  26. var sniff = false //<4>
  27. cfg := &config.Config{
  28. URL: ES_URL,
  29. Username: ES_USERNAME,
  30. Password: ES_PASSWORD,
  31. }
  32. cfg.Sniff = &sniff
  33. var client, err = elastic.NewClientFromConfig(cfg)
  34. if err != nil {
  35. fmt.Println("NewClientFromConfig Err:" + err.Error())
  36. return
  37. }
  38. var esIndex = "cygx_article"
  39. //var esType = "article"
  40. //
  41. exists, err := client.IndexExists(esIndex).Do(context.Background()) //<5>
  42. if err != nil {
  43. fmt.Println("IndexExists Err:" + err.Error())
  44. return
  45. }
  46. if !exists {
  47. _, err = client.CreateIndex(esIndex).Do(context.Background())
  48. if err != nil {
  49. fmt.Println("CreateIndex Err:" + err.Error())
  50. return
  51. }
  52. }
  53. /*
  54. 3161,3190,3226,3244,3264,3285,3310,3334,3370,3397,3418,3446,3477,3497,3526,3554
  55. */
  56. idStr := `3584,3644`
  57. idArr := strings.Split(idStr, ",")
  58. for _, v := range idArr {
  59. id, _ := strconv.Atoi(v)
  60. item, err := models.GetArticleDetailById(id)
  61. if err != nil {
  62. fmt.Println("GetArticleDetailById Err:" + err.Error())
  63. return
  64. }
  65. content := html.UnescapeString(item.Body)
  66. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  67. if err != nil {
  68. fmt.Println("create doc err:", err.Error())
  69. return
  70. }
  71. bodyText := doc.Text()
  72. item.BodyText = bodyText
  73. //新增
  74. resp, err := client.Index().Index(esIndex).Id(strconv.Itoa(item.ArticleId)).BodyJson(item).Do(context.Background())
  75. if err != nil {
  76. fmt.Println("insert es failed", err.Error())
  77. return
  78. }
  79. fmt.Println(resp.Status)
  80. }
  81. /*
  82. //根据id查询
  83. searchById, err := client.Get().Index(esIndex).Type(esType).Id("3138").Do(context.Background())
  84. if searchById.Found {
  85. body, err := searchById.Source.MarshalJSON()
  86. fmt.Println("body:",string(body))
  87. fmt.Println(err)
  88. //var resultType models.ArticleDetail
  89. //if err := json.Unmarshal(searchById.Source,&resultType); err != nil{
  90. // log.Error(err.Error())
  91. //}
  92. //fmt.Printf("search by id: %#v \n",resultType)
  93. }
  94. */
  95. ////查询index中所有的数据
  96. //var resultType models.CygxArticle
  97. //searchAll,err := client.Search(esIndex).Type(esType).Do(context.Background())
  98. //for _,item := range searchAll.Each(reflect.TypeOf(resultType)) {
  99. // language := item.(models.CygxArticle)
  100. // fmt.Printf("search by index all: %#v \n",language)
  101. //}
  102. //根据检索条件查询
  103. // boolquery := elastic.NewBoolQuery()
  104. // boolquery.Should(elastic.NewMatchQuery("Body", "专家"))
  105. // highlight := elastic.NewHighlight()
  106. // highlight = highlight.Fields(elastic.NewHighlighterField("Body"))
  107. // highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  108. // var pageSize int
  109. // pageSize = 20
  110. // searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
  111. // var result string
  112. // if searchByMatch.Hits != nil {
  113. // }
  114. // //fmt.Println(string(result))
  115. // utils.FileLog.Info("%s", string(result))
  116. //var resultType models.CygxArticle
  117. //for k,item := range searchByMatch.Each(reflect.TypeOf(resultType)) {
  118. // language := item.(models.CygxArticle)
  119. // fmt.Printf("search by match: %#v \n",language)
  120. //
  121. // fmt.Println(k)
  122. // result,err:=json.Marshal(language)
  123. // fmt.Println(err)
  124. // utils.FileLog.Info("%s",string(result))
  125. //}
  126. // Perform the search request.
  127. //searchByMatch, err := client.Search(esIndex).Type(esType).Query(query).From(1).Size(10).Do(context.Background())
  128. fmt.Println("end")
  129. }
  130. type tracelog struct{}
  131. // 实现输出
  132. func (tracelog) Printf(format string, v ...interface{}) {
  133. fmt.Printf(format, v...)
  134. }
  135. func SearchByKeyWordBack02(keyWord string) (result []*models.SearchItem, err error) {
  136. fmt.Println("keyWord:", keyWord)
  137. pageSize := 20
  138. keyWordArr, err := GetIndustryMapNameSlice(keyWord)
  139. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  140. fmt.Println(keyWordArr)
  141. fmt.Println(" keyWordArr ")
  142. if err != nil {
  143. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "GetIndustryMapNameSlice:"+err.Error(), utils.EmailSendToUsers)
  144. }
  145. //var sniff = false //<4>
  146. //cfg := &config.Config{
  147. // URL: ES_URL,
  148. // Username: ES_USERNAME,
  149. // Password: ES_PASSWORD,
  150. //}
  151. //
  152. //cfg.Sniff = &sniff
  153. //client, err := elastic.NewClientFromConfig(cfg)
  154. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  155. file := "./eslog.log"
  156. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  157. client, err := elastic.NewClient(
  158. elastic.SetURL(ES_URL),
  159. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  160. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  161. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  162. var esIndex = "cygx_article"
  163. searchMap := make(map[int]int)
  164. //boolquery := elastic.NewBoolQuery()
  165. //keyWordLen := len(keyWordArr)
  166. //n := keyWordLen
  167. //for _, v := range keyWordArr {
  168. // keyWord = v
  169. // boost := float64(n)
  170. // fmt.Println("keyWord:", keyWord)
  171. // fmt.Println("boost:", boost)
  172. // //matchQueryList = append(matchQueryList, elastic.NewMatchQuery("Title", keyWord).Boost(boost+0.2))
  173. // //matchQueryList = append(matchQueryList, elastic.NewMatchQuery("BodyText", keyWord).Boost(boost+0.1))
  174. // q1 := elastic.NewMatchQuery("Title", keyWord)
  175. // q1 = q1.Boost(boost + 0.2)
  176. // q2 := elastic.NewMatchQuery("BodyText", keyWord)
  177. // q2 = q2.Boost(boost + 0.1)
  178. // boolquery.Should(q1, q2)
  179. // n--
  180. //}
  181. keyWordStr := strings.Join(keyWordArr, ",")
  182. fmt.Println("keyWordStr ", keyWordStr)
  183. queryString := elastic.NewQueryStringQuery(`Title:(` + keyWordStr + `) BodyText:(` + keyWordStr + `)`).Analyzer("ik_smart")
  184. boolqueryJson, err := json.Marshal(queryString)
  185. fmt.Println("err:", err)
  186. fmt.Println("queryString ", string(boolqueryJson))
  187. //boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  188. highlight := elastic.NewHighlight()
  189. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  190. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  191. request := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(queryString)
  192. requestJson, err := json.Marshal(request)
  193. fmt.Println("err:", err)
  194. fmt.Println("requestJson ", string(requestJson))
  195. searchByMatch, err := request.Do(context.Background())
  196. //searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Do(context.Background())
  197. if err != nil {
  198. return result, err
  199. }
  200. if searchByMatch.Hits != nil {
  201. for _, v := range searchByMatch.Hits.Hits {
  202. articleJson, err := v.Source.MarshalJSON()
  203. if err != nil {
  204. return nil, err
  205. }
  206. article := new(models.CygxArticle)
  207. err = json.Unmarshal(articleJson, &article)
  208. if err != nil {
  209. return nil, err
  210. }
  211. if _, ok := searchMap[article.ArticleId]; !ok {
  212. searchItem := new(models.SearchItem)
  213. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  214. searchItem.Body = v.Highlight["BodyText"]
  215. var title string
  216. if len(v.Highlight["Title"]) > 0 {
  217. title = v.Highlight["Title"][0]
  218. } else {
  219. title = article.Title
  220. }
  221. searchItem.Title = title
  222. searchItem.PublishDate = article.PublishDate
  223. result = append(result, searchItem)
  224. searchMap[article.ArticleId] = article.ArticleId
  225. }
  226. }
  227. }
  228. return
  229. }
  230. func SearchByKeyWordBack(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int, err error) {
  231. keyWordArr, err := GetIndustryMapNameSlice(keyWord)
  232. if err != nil {
  233. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "GetIndustryMapNameSlice:"+err.Error(), utils.EmailSendToUsers)
  234. }
  235. var sniff = false //<4>
  236. cfg := &config.Config{
  237. URL: ES_URL,
  238. Username: ES_USERNAME,
  239. Password: ES_PASSWORD,
  240. }
  241. cfg.Sniff = &sniff
  242. client, err := elastic.NewClientFromConfig(cfg)
  243. if err != nil {
  244. return
  245. }
  246. var esIndex = indexName
  247. searchMap := make(map[int]int)
  248. for _, v := range keyWordArr {
  249. keyWord = v
  250. boolquery := elastic.NewBoolQuery()
  251. boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  252. highlight := elastic.NewHighlight()
  253. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  254. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  255. searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
  256. if err != nil {
  257. return result, 0, err
  258. }
  259. if searchByMatch.Hits != nil {
  260. for _, v := range searchByMatch.Hits.Hits {
  261. articleJson, err := v.Source.MarshalJSON()
  262. if err != nil {
  263. return nil, 0, err
  264. }
  265. article := new(models.CygxArticle)
  266. err = json.Unmarshal(articleJson, &article)
  267. if err != nil {
  268. return nil, 0, err
  269. }
  270. if _, ok := searchMap[article.ArticleId]; !ok {
  271. searchItem := new(models.SearchItem)
  272. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  273. searchItem.Body = v.Highlight["BodyText"]
  274. var title string
  275. if len(v.Highlight["Title"]) > 0 {
  276. title = v.Highlight["Title"][0]
  277. } else {
  278. title = article.Title
  279. }
  280. searchItem.Title = title
  281. searchItem.PublishDate = article.PublishDate
  282. result = append(result, searchItem)
  283. searchMap[article.ArticleId] = article.ArticleId
  284. }
  285. }
  286. }
  287. }
  288. return
  289. }
  290. func esSearch(keyWord, categoryName string) (result []*models.SearchItem, err error) {
  291. pageSize := 20
  292. var sniff = false //<4>
  293. cfg := &config.Config{
  294. URL: ES_URL,
  295. Username: ES_USERNAME,
  296. Password: ES_PASSWORD,
  297. }
  298. cfg.Sniff = &sniff
  299. client, err := elastic.NewClientFromConfig(cfg)
  300. if err != nil {
  301. return
  302. }
  303. var esIndex = "cygx_article"
  304. termsQuery := elastic.NewTermsQuery("category_name", categoryName)
  305. boolquery := elastic.NewBoolQuery()
  306. boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  307. highlight := elastic.NewHighlight()
  308. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  309. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  310. searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(termsQuery).Query(boolquery).Do(context.Background())
  311. if err != nil {
  312. return result, err
  313. }
  314. searchMap := make(map[int]int)
  315. if searchByMatch.Hits != nil {
  316. for _, v := range searchByMatch.Hits.Hits {
  317. articleJson, err := v.Source.MarshalJSON()
  318. if err != nil {
  319. return nil, err
  320. }
  321. article := new(models.CygxArticle)
  322. err = json.Unmarshal(articleJson, &article)
  323. if err != nil {
  324. return nil, err
  325. }
  326. if _, ok := searchMap[article.ArticleId]; !ok {
  327. searchItem := new(models.SearchItem)
  328. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  329. searchItem.Body = v.Highlight["BodyText"]
  330. var title string
  331. if len(v.Highlight["Title"]) > 0 {
  332. title = v.Highlight["Title"][0]
  333. } else {
  334. title = article.Title
  335. }
  336. searchItem.Title = title
  337. searchItem.PublishDate = article.PublishDate
  338. result = append(result, searchItem)
  339. searchMap[article.ArticleId] = article.ArticleId
  340. }
  341. }
  342. }
  343. return
  344. }
  345. func RemoveDuplicatesAndEmpty(a []string) (ret []string) {
  346. a_len := len(a)
  347. for i := 0; i < a_len; i++ {
  348. if (i > 0 && a[i-1] == a[i]) || len(a[i]) == 0 {
  349. continue
  350. }
  351. ret = append(ret, a[i])
  352. }
  353. return
  354. }
  355. // KeyWordArrSqlRegexp 预处理ik联想词的模糊查询语句
  356. func KeyWordArrSqlRegexp(a []string) (ret string) {
  357. a_len := len(a)
  358. for i := 0; i < a_len; i++ {
  359. if i == 0 {
  360. continue
  361. }
  362. ret += a[i] + "|"
  363. }
  364. ret = strings.TrimRight(ret, "|")
  365. return
  366. }
  367. // KeyWordArrSqlRegexp 预处理ik联想词的模糊查询语句
  368. func KeyWordArrSqlRegexpAll(a []string) (ret string) {
  369. a_len := len(a)
  370. for i := 0; i < a_len; i++ {
  371. ret += a[i] + "|"
  372. }
  373. ret = strings.TrimRight(ret, "|")
  374. //ret = "'" + ret + "'"
  375. return
  376. }
  377. func init21123() {
  378. fmt.Println("start")
  379. client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD), elastic.SetSniff(false))
  380. if err != nil {
  381. fmt.Println("err:", err)
  382. }
  383. fmt.Println(client)
  384. keyWordStr := "医疗器械"
  385. queryString := elastic.NewQueryStringQuery(`Title:(` + keyWordStr + `)`)
  386. boolqueryJson, err := json.Marshal(queryString)
  387. fmt.Println("err:", err)
  388. fmt.Println("queryString ", string(boolqueryJson))
  389. var esIndex = "cygx_article"
  390. //boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  391. highlight := elastic.NewHighlight()
  392. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  393. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  394. request := client.Search(esIndex).Highlight(highlight).Query(queryString)
  395. requestJson, err := json.Marshal(request)
  396. fmt.Println("err:", err)
  397. fmt.Println("requestJson ", string(requestJson))
  398. searchByMatch, err := request.Do(context.Background())
  399. if searchByMatch.Hits != nil {
  400. }
  401. fmt.Println(searchByMatch)
  402. fmt.Println("end")
  403. }
  404. func SearchByKeyWordQuery(keyWord string) (result []*models.SearchItem, err error) {
  405. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  406. file := "./rdlucklog/eslog.log"
  407. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  408. client, err := elastic.NewClient(
  409. elastic.SetURL(ES_URL),
  410. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  411. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  412. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  413. var esIndex = "cygx_article"
  414. //keyWordStr := "医疗"
  415. //字段相等
  416. queryString := elastic.NewQueryStringQuery("Title:医疗")
  417. //.Analyzer("ik_smart")
  418. highlight := elastic.NewHighlight()
  419. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  420. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  421. request := client.Search(esIndex).Highlight(highlight).Query(queryString)
  422. searchByMatch, err := request.Do(context.Background())
  423. if err != nil {
  424. fmt.Println("request.Do err:", err.Error())
  425. return result, err
  426. }
  427. if searchByMatch.Hits != nil {
  428. for _, v := range searchByMatch.Hits.Hits {
  429. articleJson, _ := v.Source.MarshalJSON()
  430. fmt.Println(string(articleJson))
  431. }
  432. }
  433. return
  434. }
  435. func SearchByKeyWord(keyWord string) (result []*models.SearchItem, err error) {
  436. fmt.Println("keyWord:", keyWord)
  437. keyWord = "医药"
  438. pageSize := 20
  439. keyWordArr, err := GetIndustryMapNameSlice(keyWord)
  440. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  441. fmt.Println(keyWordArr)
  442. fmt.Println(" keyWordArr ")
  443. if err != nil {
  444. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "GetIndustryMapNameSlice:"+err.Error(), utils.EmailSendToUsers)
  445. }
  446. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  447. file := "./rdlucklog/eslog.log"
  448. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  449. client, err := elastic.NewClient(
  450. elastic.SetURL(ES_URL),
  451. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  452. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  453. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  454. //var esIndex = "cygx_article"
  455. var esIndex = "article_two"
  456. searchMap := make(map[int]int)
  457. //queryString := elastic.NewQueryStringQuery(`Title:医疗 BodyText:医疗`).Analyzer("ik_smart")
  458. //queryTeerms:=elastic.NewTermsQuery("Title","医疗","费用")
  459. //queryMatchPhrase:=elastic.NewMatchPhraseQuery("Title","费用")
  460. //.Analyzer("ik_smart")
  461. //.Analyzer("ik_smart")
  462. //boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  463. boolquery := elastic.NewBoolQuery()
  464. keyLen := len(keyWordArr)
  465. n := float64(keyLen)
  466. matchArr := make([]elastic.Query, 0)
  467. for _, v := range keyWordArr {
  468. if v != "" {
  469. matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  470. matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  471. matchArr = append(matchArr, matchq1)
  472. matchArr = append(matchArr, matchq2)
  473. }
  474. n--
  475. }
  476. //matchArr=append(matchArr,matchq1)
  477. //matchArr=append(matchArr,matchq2)
  478. boolquery.Should(matchArr...)
  479. //boolquery.Must(elastic.NewMatchQuery("BodyText", keyWord).Boost(1).Analyzer("ik_smart"))
  480. highlight := elastic.NewHighlight()
  481. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  482. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  483. //request := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(queryString)
  484. request := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery)
  485. searchByMatch, err := request.Do(context.Background())
  486. fmt.Println(searchByMatch, err)
  487. //searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Do(context.Background())
  488. if err != nil {
  489. return result, err
  490. }
  491. fmt.Println(searchByMatch.Status, searchByMatch.TotalHits())
  492. if searchByMatch.Hits != nil {
  493. for _, v := range searchByMatch.Hits.Hits {
  494. articleJson, err := v.Source.MarshalJSON()
  495. if err != nil {
  496. return nil, err
  497. }
  498. article := new(models.CygxArticle)
  499. err = json.Unmarshal(articleJson, &article)
  500. if err != nil {
  501. return nil, err
  502. }
  503. if _, ok := searchMap[article.ArticleId]; !ok {
  504. searchItem := new(models.SearchItem)
  505. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  506. searchItem.Body = v.Highlight["BodyText"]
  507. var title string
  508. if len(v.Highlight["Title"]) > 0 {
  509. title = v.Highlight["Title"][0]
  510. } else {
  511. title = article.Title
  512. }
  513. searchItem.Title = title
  514. searchItem.PublishDate = article.PublishDate
  515. result = append(result, searchItem)
  516. searchMap[article.ArticleId] = article.ArticleId
  517. }
  518. }
  519. }
  520. return
  521. }
  522. func AddMap() {
  523. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  524. file := "./rdlucklog/eslog.log"
  525. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  526. client, err := elastic.NewClient(
  527. elastic.SetURL(ES_URL),
  528. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  529. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  530. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  531. if err != nil {
  532. fmt.Println("NewClient Err:", err.Error())
  533. }
  534. bodyJson := `{
  535. "mappings": {
  536. "properties": {
  537. "ArticleId": {
  538. "type": "integer"
  539. },
  540. "Title": {
  541. "type": "text",
  542. "analyzer": "ik_smart"
  543. },
  544. "BodyText": {
  545. "type": "text",
  546. "analyzer": "ik_smart"
  547. }
  548. }
  549. }
  550. }`
  551. //var esMappingIndex = "article_mapping"
  552. var esIndex = "article_two"
  553. a := client.IndexAnalyze().Index(esIndex)
  554. analyzeBody, err := json.Marshal(a)
  555. fmt.Println(string(analyzeBody))
  556. exists, err := client.IndexExists(esIndex).Do(context.Background()) //<5>
  557. if err != nil {
  558. fmt.Println("IndexExists Err:" + err.Error())
  559. return
  560. }
  561. fmt.Println("exists:", exists)
  562. if !exists {
  563. _, err = client.CreateIndex(esIndex).BodyJson(bodyJson).Do(context.Background())
  564. //BodyJson(bodyJson).Do(context.Background())
  565. if err != nil {
  566. fmt.Println("CreateIndex Err:" + err.Error())
  567. return
  568. }
  569. }
  570. item, err := models.GetArticleDetailTestById(3546)
  571. if err != nil {
  572. fmt.Println("GetArticleDetailById Err:" + err.Error())
  573. return
  574. }
  575. content := html.UnescapeString(item.Body)
  576. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  577. if err != nil {
  578. fmt.Println("create doc err:", err.Error())
  579. return
  580. }
  581. bodyText := doc.Text()
  582. item.BodyText = bodyText
  583. //新增
  584. resp, err := client.Index().Index(esIndex).Id(strconv.Itoa(item.ArticleId)).BodyJson(item).Do(context.Background())
  585. if err != nil {
  586. fmt.Println("insert es failed", err.Error())
  587. return
  588. }
  589. fmt.Println(resp)
  590. }