厚街网站建设价格,现在网站都是拿什么软件做的,网站ip解析,青岛市建设局网站Elasticsearch 8.x Python 官方客户端实战教程
一、Elasticsearch 基础概念#xff08;工程视角#xff09;
1. Index#xff08;索引#xff09;
类似 数据库中的表一个 Index 通常对应一个业务实体集合#xff0c;例如#xff1a; user_logsorder_records
⚠️ 工…Elasticsearch 8.x Python 官方客户端实战教程一、Elasticsearch 基础概念工程视角1. Index索引类似数据库中的表一个 Index 通常对应一个业务实体集合例如user_logsorder_records⚠️工程建议一个索引只服务一种查询模式不要把“所有数据”塞进一个 index2. Document文档一条 JSON 数据每条文档都有_id{user_id:u123,action:login,timestamp:2025-01-01T10:00:00}3. Mapping字段结构相当于表结构定义决定是否可搜索是否可聚合是否支持排序❗一旦字段类型确定几乎不可修改4. Shard / Replica分片 副本shard数据拆分单元影响写入 查询性能replica副本高可用 查询吞吐通用建议中小业务1~3shards副本数1二、Elasticsearch 8.x 架构与安全机制从8.x 开始默认开启安全机制HTTPS用户认证API 访问权限Python 客户端必须显式配置认证三、Python 官方客户端安装8.xpipinstallelasticsearch8.12.0验证版本fromelasticsearchimport__version__print(__version__)四、Python 连接 Elasticsearch生产可用1. 基础连接用户名 密码fromelasticsearchimportElasticsearch esElasticsearch(hosts[https://localhost:9200],basic_auth(elastic,your_password),verify_certsFalse# 本地测试可关闭生产请开启)print(es.info())2. HTTPS CA 证书生产推荐esElasticsearch(hosts[https://es-prod.example.com:9200],basic_auth(elastic,password),ca_certs/etc/elasticsearch/certs/http_ca.crt)五、索引设计与创建真实工程示例1. 索引 Mapping 设计INDEX_NAMEuser_action_logsmapping{settings:{number_of_shards:2,number_of_replicas:1},mappings:{properties:{user_id:{type:keyword},action:{type:keyword},message:{type:text},ip:{type:ip},created_at:{type:date}}}}2. 创建索引幂等ifnotes.indices.exists(indexINDEX_NAME):es.indices.create(indexINDEX_NAME,bodymapping)六、数据写入单条 批量1. 单条写入indexes.index(indexINDEX_NAME,idu123_001,document{user_id:u123,action:login,message:user login success,ip:127.0.0.1,created_at:2025-01-01T10:00:00})2. 批量写入bulk生产必用fromelasticsearch.helpersimportbulk actions[]foriinrange(1000):actions.append({_index:INDEX_NAME,_id:fu123_{i},_source:{user_id:u123,action:click,message:fclick{i},ip:127.0.0.1,created_at:2025-01-01T10:00:00}})bulk(es,actions,request_timeout60)工程建议单批 500~2000 条明确_id保证幂等七、查询核心能力1. 基础查询reses.search(indexINDEX_NAME,query{term:{action:login}})2. Bool 查询真实业务reses.search(indexINDEX_NAME,query{bool:{must:[{term:{user_id:u123}}],filter:[{range:{created_at:{gte:now-1d}}}]}},size20,sort[{created_at:desc}])3. 聚合查询reses.search(indexINDEX_NAME,size0,aggs{action_count:{terms:{field:action}}})八、深分页解决方案❌ from size禁止大页超过 10k 会严重影响性能search_after推荐reses.search(indexINDEX_NAME,size10,sort[{created_at:desc},{_id:desc}])last_sortres[hits][hits][-1][sort]res_nextes.search(indexINDEX_NAME,size10,search_afterlast_sort,sort[{created_at:desc},{_id:desc}])九、工程级 Client 封装示例classESClient:def__init__(self,hosts,username,password,ca_certsNone):self.clientElasticsearch(hostshosts,basic_auth(username,password),ca_certsca_certs,)defindex_doc(self,index,doc_id,doc):returnself.client.index(indexindex,iddoc_id,documentdoc)defsearch(self,index,query,size10):returnself.client.search(indexindex,queryquery,sizesize)十、常见踩坑总结8.x❌ 使用body写 search已废弃❌ 忽略 HTTPS / 认证❌ 动态 Mapping 失控❌ 大分页 from size十一、结语如果你正确设计索引使用 bulk 写入使用 bool filter 查询合理分页