go-elasticsearch操作
一、ES连接
package es import ( "bytes" "context" "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v6" "log" ) func Index() { addresses := []string{"http://127.0.0.1:9200", "http://127.0.0.1:9201"} config := elasticsearch.Config{ Addresses: addresses, Username: "", Password: "", CloudID: "", APIKey: "", } // new client es, err := elasticsearch.NewClient(config) if err != nil { panic(err) } }
二、index索引增、删
创建索引:es_client.CreateIndex(indexname).Do(context.Background())
删除索引:es_client.DeleteIndex(indexname).Do(context.Background())
三、索引_aliases
索引别名就像一个快捷方式或软连接,可以指向一个或多个索引。
别名 带给我们极大的灵活性,允许我们做下面这些:
- 给多个索引分组 (例如, last_three_months)
- 给索引的一个子集创建视图
- 在运行的集群中可以无缝的从一个索引切换到另一个索引
四、索引模板
Index Template 索引模板,顾名思义,就是创建索引的模具,其中可以定义一系列规则来帮助我们构建符合特定业务需求的索引的 mappings 和 settings,通过使用 Index Template 可以让我们的索引具备可预知的一致性
常见的场景: 分割索引
分割索引就是根据时间间隔把一个业务索引切分成多个索引。
比如 把order_info 变成 order_info_20200101,order_info_20200102 ……
这样做的好处有两个:
结构变化的灵活性:因为elasticsearch不允许对数据结构进行修改。但是实际使用中索引的结构和配置难免变化,那么只要对下一个间隔的索引进行修改,原来的索引位置原状。这样就有了一定的灵活性。
查询范围优化: 因为一般情况并不会查询全部时间周期的数据,那么通过切分索引,物理上减少了扫描数据的范围,也是对性能的优化。
创建模板:
创建模板+别名
其中 “index_patterns”: [“movie_test*”], 的含义就是凡是往movie_test开头的索引写入数据时,如果索引不存在,那么es会根据此模板自动建立索引。
在 “aliases” 中用{index}表示,获得真正的创建的索引名。

五、打印log![]()
六、示例:
python示例:
class EsHelper: def __init__(self, addr, index_name, index_alias: str, doc_type="_doc"): self.es = Elasticsearch(hosts=addr) self.index_name = index_name self.doc_type = doc_type self.index_alias = index_alias self.create_template_not_exist(self.index_alias, self.doc_type) if not self.check_index_exist(): self.create_index() def check_index_exist(self) -> bool: return self.es.indices.exists(self.index_name) def create_index(self): self.es.indices.create(index=self.index_name) self.es.indices.put_alias(index=self.index_name, name=self.index_alias) def create_template_not_exist(self, detect_template_name: str, doc_type: str = "_doc"): exist = self.es.indices.exists_template(detect_template_name) if not exist: body_str = TEMPLATE % (self.index_alias, self.index_alias, self.doc_type) body = json.loads(body_str) self.es.indices.put_template(detect_template_name, body) def bulk_insert(self, action: Iterator): bulk(self.es, action, chunk_size=1)
posted on 2021-11-22 13:21 myworldworld 阅读(753) 评论(0) 收藏 举报