background/model/port.go

82 lines
1.8 KiB
Go
Raw Normal View History

package model
import (
"background/db"
"github.com/go-openapi/errors"
json "github.com/json-iterator/go"
"qiniupkg.com/x/log.v7"
"strings"
"ubntgo/logger"
)
type Field struct {
Field string `sql:"Field"`
Type string `sql:"Type"`
Key string `sql:"Key"`
}
func MysqlToElasticSearchMapping(types string,Key string) string{
if Key == "PRI"{
return "keyword"
}
if(strings.Contains(types,"int(")){
return "interger"
}
if(strings.Contains(types,"longblob")){
return "text"
}
if(strings.Contains(types,"varchar")){
return "text"
}
if(strings.Contains(types,"datetime")){
return "date"
}
return ""
}
/*
`"mappings":{
"hardware":{
"properties":{
"id":{"type":"keyword"},
"name":{"type":"keyword"},
"desc":{"type":"text"},
"pic":{"type":"doc"},
"doc":{"type":"doc"}
}
}
}`
*/
// 不同类型db之间进行缓存
func PortDocumentToElasticsearch(tblname string ) error{
columns := []Field{}
e := db.GetMysqlClient().Query2("describe " + tblname,&columns)
if nil != e{
logger.Debug(e.Error())
return e
}
if existed,_ := db.GetElastic().IndexExisted("doc");existed{
return errors.New(203,"data existed")
}
mapping := map[string]interface{}{}
indexprops := map[string]interface{}{}
mapping["mapping"] = map[string]interface{}{}
mapping["mapping"].(map[string]interface{})[tblname] = map[string]interface{}{}
mapping["mapping"].(map[string]interface{})[tblname].(map[string]interface{})["properties"] = indexprops
for _,v := range columns{
indexprops[v.Field] = map[string]string{};
indexprops[v.Field].(map[string]string)["type"] = MysqlToElasticSearchMapping(v.Type,v.Key)
}
dat,e := json.Marshal(mapping)
if nil != e{
log.Print(e.Error())
}
e = db.GetElastic().CreateIndex(tblname,string(dat))
if nil != e{
log.Print(e.Error())
}
return nil
}