diff --git a/db/elasticEngine.go b/db/elasticEngine.go index 499a41a..97cb4ca 100644 --- a/db/elasticEngine.go +++ b/db/elasticEngine.go @@ -6,6 +6,8 @@ import ( "gopkg.in/olivere/elastic.v3" "qiniupkg.com/x/log.v7" "reflect" + "context" + ) const( ERROR_PTR = "nullpointer error" @@ -100,3 +102,82 @@ func (p *ElkEngine)Update(index string,types string,id string,data map[string]in } return errors.New(ERROR_PTR) } + +// 创建 elasticSearch 的 Mapping +func (p *ElkEngine)InitMapping(esIndexName string, esTypeName string, typeMapping string) error{ + var err error + indexMapping := helper.GetEsIndexMapping() + //ctx := context.Background() + + // Use the IndexExists service to check if a specified index exists. + exists, err := p.cli.IndexExists(esIndexName).Do() + if err != nil { + log.Println("IndexExists" + err.Error()) + return err + } + //log.Println("es index: " + esIndexName) + //log.Println("es type: " + esTypeName) + //log.Println("es index mapping: " + indexMapping) + //log.Println("es type mapping: " + typeMapping) + if !exists { + log.Println("es index not exists: " + esIndexName) + // Create a new index. + createIndex, err := p.cli.CreateIndex(esIndexName).Body(indexMapping).Do() + if err != nil { + log.Println("CreateIndex" + err.Error()) + return err + } + if !createIndex.Acknowledged { + // Not acknowledged + return errors.New("create index:" + esIndexName + ", not Ack nowledged") + } + } + /** + * 判断 type 是否存在 + exists, err = client.TypeExists().Index(esIndexName).Type(esTypeName).Do(ctx) + if err != nil { + return err + } + if !exists { + + } + */ + // PutMapping() *IndicesPutMappingService + + putresp, err := p.cli.PutMapping().Index(esIndexName).Type(esTypeName).BodyString(typeMapping).Do() + // 新建 mapping + //indicesCreateResult, err := elastic.NewIndicesCreateService(client).Index(esIndexName).BodyString(mapping).Do(ctx) + if err != nil { + log.Println("NewIndicesCreateService" + err.Error()) + return err + } + if !putresp.Acknowledged { + // Not acknowledged + return errors.New("create mapping fail, esIndexName:" + esIndexName + ", esTypeName:" + esTypeName + ", not Ack nowledged") + } + + // 插入数据 + /* + type WholeBrowserData struct { + BrowserId string `json:"browser_id"` + BrowserName string `json:"browser_name"` + } + + // Index a tweet (using JSON serialization) + wholeBrowserData := WholeBrowserData{BrowserId: "BrowserId", BrowserName: "BrowserName" } + put1, err := client.Index(). + Index(esIndexName). + Type(esTypeName). + Id("1"). + BodyJson(wholeBrowserData). + Do(ctx) + if err != nil { + // Handle error + panic(err) + } + log.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type) + */ + + + return err +} \ No newline at end of file