GolangES使用记录(01)

1、安装Es

docker run -d --name elasticsearch --net elk -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.17.0

2、第三方库

go get github.com/olivere/elastic

3、快速开始

package main

import (
	"github.com/olivere/elastic/v7"
	"log"
)

func main() {
	esClient, err := elastic.NewClient(elastic.SetSniff(false),
		// 设置ES服务地址,支持多个地址
		elastic.SetURL("http://127.0.0.1:9200"))
	if err != nil {
		log.Println("es err", err)
	}
	log.Println(esClient.IsRunning())
}

//  true

4、手动创建索引

package main

import (
	"context"
	"github.com/olivere/elastic/v7"
	"log"
)

func main() {
	esClient, err := elastic.NewClient(elastic.SetSniff(false),
		// 设置ES服务地址,支持多个地址
		elastic.SetURL("http://127.0.0.1:9200"))
	if err != nil {
		log.Println("es err", err)
	}
	log.Println(esClient.IsRunning())
	mapping := `
	{
	  "settings": {
		"number_of_shards": 5,
		"number_of_replicas": 1
	  },
	  "mappings": {
		"properties": {
		  "id": {
			"type": "long"
		  },
		  "name": {
			"type": "text"
		  },
		  "code": {
			"type": "text"
		  }
		}
	  }
	}
		`
	res, err := esClient.CreateIndex("test1").Body(mapping).Do(context.Background())
	if err != nil {
		log.Println(err)
	}
	log.Println(res)

	indexRes, err := esClient.GetMapping().Index("test1").Do(context.Background())
	if err != nil {
		log.Println(err)
	}
	log.Println(indexRes)
}

5、示例

业务上一般都会从数据库通过中间件将数据同步到ES中,因为各自业务复杂度不同,我们通常会遇到各自合表的情况,下面以订单表为例,简单演示下

// Order 订单
type Order struct {
	Id         int64     `json:"id"`
	OrderNo    string    `json:"orderNo"`
	Created    time.Time `json:"created"`
	TotalPrice float64   `json:"totalPrice"` // 总价格
	Payment    float64   `json:"payment"`    // 实际价格
}

// SubOrder 子订单
type SubOrder struct {
	Id        int64   `json:"id"`
	OrderNo   string  `json:"orderNo"`
	Name      string  `json:"name"`
	Code      string  `json:"code"`
	Number    int64   `json:"number"`    // 数量
	UnitPrice float64 `json:"unitPrice"` // 单价
	Cost      float64 `json:"cost"`      // 成本
	Total     float64 `json:"total"`     // 合计
}

订单表和订单子表通过订单号OrderNo进行关联,可能会出现一对多的情况,这种情况下的索引怎么创建呢

{
  "settings": {
    "number_of_shards": 5,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "orderNo": {
        "type": "text"
      },
      "created": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time||epoch_millis"
      },
      "totalPrice": {
        "type": "double"
      },
      "payment": {
        "type": "double"
      },
      "sub_order": {
        "type": "nested",
        "properties": {
          "sub_order_id": {
            "type": "long"
          },
          "sub_order_orderNo": {
            "type": "text"
          },
          "sub_order_name": {
            "type": "text"
          },
          "sub_order_number": {
            "type": "long"
          },
          "sub_order_unitPrice": {
            "type": "double"
          },
          "sub_order_cost": {
            "type": "double"
          },
          "sub_order_total": {
            "type": "double"
          }
        }
      }
    }
  }
}

完整示例代码如下:

package main

import (
	"context"
	"github.com/olivere/elastic/v7"
	"log"
	"time"
)

var Es *elastic.Client

// Order 订单
type Order struct {
	Id         int64     `json:"id"`
	OrderNo    string    `json:"orderNo"`
	Created    time.Time `json:"created"`
	TotalPrice float64   `json:"totalPrice"` // 总价格
	Payment    float64   `json:"payment"`    // 实际价格
}

// SubOrder 子订单
type SubOrder struct {
	Id        int64   `json:"id"`
	OrderNo   string  `json:"orderNo"`
	Name      string  `json:"name"`
	Number    int64   `json:"number"`    // 数量
	UnitPrice float64 `json:"unitPrice"` // 单价
	Cost      float64 `json:"cost"`      // 成本
	Total     float64 `json:"total"`     // 合计
}

func init() {
	var err error
	Es, err = elastic.NewClient(elastic.SetSniff(false),
		// 设置ES服务地址,支持多个地址
		elastic.SetURL("http://127.0.0.1:9200"))
	if err != nil {
		log.Println("es err", err)
	}
	log.Println(Es.IsRunning())
}

func main() {
	// 创建索引
	CreateIndex()
}

func CreateIndex() {
	mapping := `
			{
  "settings": {
    "number_of_shards": 5,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "orderNo": {
        "type": "text"
      },
      "created": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time||epoch_millis"
      },
      "totalPrice": {
        "type": "double"
      },
      "payment": {
        "type": "double"
      },
      "sub_order": {
        "type": "nested",
        "properties": {
          "sub_order_id": {
            "type": "long"
          },
          "sub_order_orderNo": {
            "type": "text"
          },
          "sub_order_name": {
            "type": "text"
          },
          "sub_order_number": {
            "type": "long"
          },
          "sub_order_unitPrice": {
            "type": "double"
          },
          "sub_order_cost": {
            "type": "double"
          },
          "sub_order_total": {
            "type": "double"
          }
        }
      }
    }
  }
}

		`

	res, err := Es.CreateIndex("order").BodyString(mapping).Do(context.Background())
	if err != nil {
		log.Println(err)
	}
	log.Println(res)

	indexRes, err := Es.GetMapping().Index("order").Do(context.Background())
	if err != nil {
		log.Println(err)
	}
	log.Println(indexRes)
}