elasticsearch使用river同步mysql数据

本文介绍如何使用 MySQL River 插件将 MySQL 数据同步至 Elasticsearch。包括安装配置、创建索引映射、运行 River 实现全量及增量数据同步等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

====== mysql的river介绍======
      - 什么是river?river代表es的一个数据源,也是其它存储方式(如:数据库)同步数据到es的一个方法。它是以插件方式存在的一个es服务,通过读取river中的数据并把它索引到es中,官方的river有couchDB的,RabbitMQ的,Twitter的,Wikipedia的。这里主要研究针对mysql的river。
      - mysql的river插件:mysql的river安装见https://github.com/jprante/elasticsearch-river-jdbc,就不具体介绍了。
      - 实践测试:
      * 环境:
       服务器172.16.170.21   数据库:profile 表user
      * 创建索引
        curl -XPUT 'http://localhost:9200/profile'
      * 创建数据表与索引映射
curl -XPUT 'http://localhost:9200/profile/user/_mapping' -d '
{
    "user": {
        "properties": {
            "id": {
                "type": "string",
                "store": "yes"
            },
            "name": {
                "type": "string",
                "store": "yes"
            },
            "login_name": {
                "type": "string",
                "store": "yes"
            }
        }
    }
}'


      * 运行river同步数据


curl -XPUT 'http://localhost:9200/_river/who_jdbc_river/_meta' -d '{
    "type": "jdbc",
    "jdbc": {
        "driver": "com.mysql.jdbc.Driver",
        "url": "jdbc:mysql://localhost:3306/profile",
        "user": "root",
        "password": "root",
        "sql": "select id as _id,name,login_name from user",
        "index": "profile",
        "type": "user",
        "bulk_size": 100,
        "max_bulk_requests": 30,
        "bulk_timeout": "10s",
        "flush_interval": "5s",
        "schedule": "0 0-59 0-23 ? * *"
    }
}'


      * 增量更新索引
增量更新,表需要维护时间戳,发现时间戳更新的列需要更新
curl -XPUT 'http://localhost:9200/_river/who_jdbc_river/_meta' -d '{
    "type": "jdbc",
    "jdbc": {
        "driver": "com.mysql.jdbc.Driver",
        "url": "jdbc:mysql://localhost:3306/profile",
        "user": "root",
        "password": "root",
        "sql": [
            {
                "statement": "select id as _id,name,login_name from user where mytimestamp > ?",
                "parameter": [
                    "$river.state.last_active_begin"
                ]
            }
        ],
        "index": "profile",
        "type": "user",
        "bulk_size": 100,
        "max_bulk_requests": 30,
        "bulk_timeout": "10s",
        "flush_interval": "5s",
        "schedule": "0 0-59 0-23 ? * *"
    }
}'



删除river

curl -XDELETE 'localhost:9200/_river/report_jdbc_river'

<think>嗯,用户正在深入学习Elasticsearch,现在聚焦在MySQL数据同步这个具体场景。从引用内容看,用户已经查阅了多种方案,但需要更落地的配置指导。用户可能是个中高级开发者,正在搭建搜索系统,时间应该比较紧张——引用里特意标注了“不是真正需求”,说明用户需要跳过理论直接实操。 同步方案的选择其实隐含了用户没明说的需求:实时性要求。引用[2]提到双写模式适合强一致,引用[4]的go-mysql-elasticsearch工具则适合准实时。需要帮用户做决策:如果业务容忍秒级延迟,选Binlog方案更稳妥;如果是金融级实时,就得忍受双写的复杂度。 注意到用户贴了river.toml配置片段,但缩进混乱,可能复制时格式丢失。需要强调几个关键参数:my_addr的3306端口是否开放,bulk_size在128这个值适合中型集群,小集群应该调低。filter字段容易被忽略——很多用户同步了多余字段导致ES映射冲突。 安全方面要提醒用户,引用[4]的示例里密码明文存储是大忌,应该补充environment变量或Vault集成方案。还有那个aliyundrive的项目链接(引用[3])已经失效,不必再提。 最后生成的四个问题中,“分片失衡”和“CPU飙升”是用户上次问题的延续,保持连续性很重要。但安全认证那个问题可能超纲了,用户当前明显更关注同步——不过留着也没坏处,说不定是下一个需求。</think>以下是ElasticsearchMySQL数据同步的**详细配置指南**,整合主流方案与最佳实践: --- ### 一、同步方案选择 | **方案** | **实时性** | **复杂度** | **适用场景** | |-------------------|------------|------------|--------------------------| | 应用层双写 | 高 | 高 | 强一致性要求(如交易系统) | | Binlog日志同步 | 中高 | 中 | 准实时同步(推荐方案) | | 定时任务同步 | 低 | 低 | 对延迟不敏感的场景 | --- ### 二、主流方案配置详解 #### ▶ 方案1:Binlog日志同步(推荐) **工具**:`go-mysql-elasticsearch`[^4] **原理**:监听MySQL的Binlog,实时同步到ES ```bash # 安装步骤 go get github.com/siddontang/go-mysql-elasticsearch cd $GOPATH/src/github.com/siddontang/go-mysql-elasticsearch make ``` **配置文件** (`/etc/river.toml`): ```toml # MySQL连接配置 my_addr = "192.168.1.100:3306" my_user = "db_user" my_pass = "SecurePass123!" # ES连接配置 es_addr = "192.168.1.101:9200" es_user = "elastic" es_pass = "es_password" # 同步规则 [[source]] schema = "shop_db" # 数据库名 tables = ["products"] # 表名 [[rule]] schema = "shop_db" table = "products" index = "shop_products" # ES索引名 type = "_doc" # ES类型 filter = ["id", "name", "price", "description"] # 同步字段 ``` **启动命令**: ```bash ./bin/go-mysql-elasticsearch -config=/etc/river.toml ``` #### ▶ 方案2:应用层双写 **代码示例(Spring Boot)**: ```java @Service public class ProductService { private final ProductRepository mySQLRepo; private final ElasticsearchRestTemplate esTemplate; // 双写方法 @Transactional public void saveProduct(Product product) { // 写入MySQL mySQLRepo.save(product); // 写入Elasticsearch IndexQuery query = new IndexQueryBuilder() .withId(product.getId().toString()) .withObject(product) .build(); esTemplate.index(query); } } ``` > 需处理分布式事务问题(如本地消息表)[^2] #### ▶ 方案3:Logstash定时同步 **配置模板** (`mysql-to-es.conf`): ```ruby input { jdbc { jdbc_driver_library => "/path/to/mysql-connector-java.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_connection_string => "jdbc:mysql://192.168.1.100:3306/shop_db" jdbc_user => "db_user" jdbc_password => "SecurePass123!" schedule => "*/5 * * * *" # 每5分钟同步 statement => "SELECT * FROM products WHERE updated_at > :sql_last_value" } } output { elasticsearch { hosts => ["192.168.1.101:9200"] index => "shop_products" document_id => "%{id}" } } ``` --- ### 三、关键注意事项 1. **数据一致性保障** - Binlog方案:需监控`gtid`位置点,断点续传 - 双写方案:添加重试机制 + 死信队列 - 冲突解决:使用`version`字段做乐观锁控制[^1] 2. **性能优化** ```toml # go-mysql-elasticsearch配置 bulk_size = 500 # 批量提交大小 flush_bulk_time = "1s" # 最大等待时间 ``` 3. **字段映射规则** - MySQL的`DATETIME` → ES的`date`类型 - MySQL的`DECIMAL` → ES的`scaled_float` - 文本字段需指定分词器:`"analyzer": "ik_max_word"` --- ### 四、故障排查技巧 ```bash # 查看同步状态 curl -XGET 'http://es-host:9200/_cat/indices?v' # 检查未同步数据 SELECT * FROM products WHERE id NOT IN ( SELECT _id FROM shop_products ) LIMIT 100; ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值