MySQL表结构转换为ES索引Mapping

这篇具有很好参考价值的文章主要介绍了MySQL表结构转换为ES索引Mapping。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

背景

日常开发过程中肯定会存在MySQL表数据迁移至ES的情况,以canal为例,数据迁移时需要提前在ES中创建索引Mapping,但是如果碰到字段特别的表时,创建Mapping将是一件耗费心神的事情。为了解决这些重复工作,我使用Python编写了一个脚本,自动将MySQL中的表结构同步到ES中,本脚本只同步表结构,并不同步表数据,如需同步数据可以采用canal或者logstash等方式进行同步

脚本内容

如果不需要直接同步到es中,需要注释脚本最后一行,该脚本会将转换后的mapping信息打印到控制台中

MySQL表结构转换为ES索引Mapping,ElasticSearch,mysql,elasticsearch,python文章来源地址https://www.toymoban.com/news/detail-780511.html

import mysql.connector
import requests
import json

# MySQL连接配置
mysql_config = {
    'host': '127.0.0.1',
    'port': '3306',
    'user': 'root',
    'password': '123456',
    'database': 'test'
}

# Elasticsearch配置
es_host = '127.0.0.1'
es_port = '9200'
es_index = 'order1'


# 新版本es不需求type字段
# es_type = '_doc'

def fetch_mysql_table_fields(mysql_config):
    connection = mysql.connector.connect(**mysql_config)
    cursor = connection.cursor()

    # 获取MySQL表字段信息,指定需要转换得表名
    cursor.execute(f"DESCRIBE {"`order`"}")
    fields = cursor.fetchall()

    cursor.close()
    connection.close()

    return fields


def generate_es_mapping(fields):
    mapping = {
        "mappings": {
            "properties": {}
        }
    }

    for field in fields:
        field_name = field[0]
        field_type = field[1]

        # 根据MySQL字段类型设置Elasticsearch映射类型
        es_field_type = "text"  # 默认为文本类型
        if "int" in field_type:
            es_field_type = "integer"
        elif "bigint" in field_type:
            es_field_type = "long"
        elif "tinyint" in field_type:
            es_field_type = "short"
        elif "float" in field_type:
            es_field_type = "float"
        elif "double" in field_type:
            es_field_type = "double"
        elif "decimal" in field_type:
            es_field_type = "double"
        elif "date" in field_type or "datetime" in field_type or "timestamp" in field_type or "time" in field_type:
            es_field_type = "date"
        elif "json" in field_type:
            es_field_type = "object"

        # 这里可以根据需要添加更多类型的映射

        mapping["mappings"]["properties"][field_name] = {
            "type": es_field_type
        }

    return mapping


def print_es_mapping(mapping):
    print(json.dumps(mapping, indent=2))


def create_es_index_mapping(es_host, es_port, es_index, mapping):
    url = f"http://{es_host}:{es_port}/{es_index}"
    headers = {'Content-Type': 'application/json'}
    payload = json.dumps(mapping)

    response = requests.put(url, headers=headers, data=payload)

    if response.status_code == 200:
        print(f"Elasticsearch index mapping created for index '{es_index}'")
    else:
        print(f"Failed to create Elasticsearch index mapping. Status code: {response.status_code}")
        print(response.text)


if __name__ == "__main__":
    # 获取MySQL表字段信息
    table_fields = fetch_mysql_table_fields(mysql_config)

    # 生成Elasticsearch Mapping
    es_mapping = generate_es_mapping(table_fields)

    # 打印Elasticsearch Mapping到控制台
    print_es_mapping(es_mapping)

    # 创建Elasticsearch Index Mapping
    create_es_index_mapping(es_host, es_port, es_index, es_mapping)

到了这里,关于MySQL表结构转换为ES索引Mapping的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 深入理解Elasticsearch的索引映射(mapping)

    当我们谈论Elasticsearch时,索引映射是一个核心概念,它定义了如何存储和检索数据。在Elasticsearch 7.6及更高版本中,映射提供了一系列强大的功能,使您能够精确地控制数据的结构和行为。本文将详细介绍映射的关键属性、用途以及如何正确设置和优化它。 在Elasticsearch中,

    2024年02月22日
    浏览(38)
  • Elasticsearch Mapping字段未支持索引导致搜索失效

    生产上Es根据一个时间字段搜索,却没有返回数据 根据命令: GET indexName/_mapping 查看 count_name设置了 “index”: false 导致根据该字段搜索导致索引不生效。 ES的mappings 定义好了生成索引后是不支持修改现有的字段的,只能新增属性。 使用 reindex 命令处理 1、运行命令: GET ind

    2024年02月11日
    浏览(26)
  • Elasticsearch索引优化指南:分片、副本、mapping和analyzer

    Elasticsearch是一个开源的分布式搜索引擎,它的数据存储和查询速度非常快。然而,在面对大规模的数据集和高并发访问时,Elasticsearch的性能也可能受到一些影响。为了最大程度地提高Elasticsearch的性能,我们需要对索引进行优化。本篇博客将介绍Elasticsearch索引优化的几个关键

    2024年02月20日
    浏览(38)
  • 【ELK03】ES 索引的Mapping映射详解、数据类型和settings属性设置

    映射(MAPPING)就是es中一个决定了文档如何存储,如何生成索引,字段各种类型定义的过程.类似于我们在关系型数据库中创建一个 表格数据之前先定义表格有哪些字段,每个字段是什么类型 ,然后数据会按照这个配置写入表格,ES中同样是这个过程,它由两种映射组成.一个是 动态映射

    2024年02月03日
    浏览(39)
  • es elasticsearch 九 索引index 定制分词器 type结构后期弃用原因 定制动态映射 动态映射模板 零停机重建索引

    目录 索引index 定制分词器 Type底层结构及弃用原因 定制 dynamic mapping 定制dynamic mapping template 动态映射模板 零停机重建索引 生产环境应该度别名数据 索引index Put /index Stings 分片 Mapping 映射 Aliases 别名 增加 Put my_index2 {        \\\"settings\\\":{           \\\"number_of_shards\\\":3,      

    2024年02月06日
    浏览(31)
  • 【ElasticSearch】索引数据mapping嵌套深度过大导致Stackoverflow问题排查

    集群所有数据节点频繁因为StackOverflowError的错误挂掉,启动后还会挂掉,StackOverflowError异常栈如下 通过堆栈可以看出是写入线程池[write]发生的Stackoverflow,并且可能是在解析mapping的过程发生的,通过ObjectMapper类推断是Object类型数据写入导致的。因此通过拉取集群内所有索引的

    2024年02月03日
    浏览(31)
  • es elasticsearch 八 mapping 映射 、复杂数据类型

    目录 Mapping 映射 复杂数据类型 Mapping 映射 精确匹配 必须和对应字段值安全一致才可查出 全文检索 缩写搜索全程、格式转换 大小写 同义词 全文检索核心原理 分词,初步的倒排索引的建立 重建倒排索引 时态转换、重复数的转换、同义词的转换、大小写的转换 分词器 analy

    2024年02月07日
    浏览(46)
  • 【Elasticsearch学习笔记二】es的Mapping字段映射、Mapping字段常用类型、Mapping映射的创建、查看和更新、es数据迁移、ik分词器

    目录 1、Mapping字段映射概述 2、Mapping字段常用类型 3、映射中对时间类型详解 1)采取自动映射器来映射 2)手工映射提前指定日期类型 4、ES的keyword的属性ignore_above 5、Mapping映射的查看和创建 1)查看mapping信息:GET 索引名/_mapping 2)创建映射:PUT /索引名 3) 查看所有索引映

    2024年01月20日
    浏览(51)
  • 【ElasticSearch-基础篇】Mapping结构

    Mapping 类似 mysql 中的 schema 的定义 用于定义索引属性字段的名称、字段的数据类型 (如 text , long , keyword…)、字段的倒排索引相关配置 一个Mapping 属于一个索引的Type、每个文档都属于一个Type es7.0开始, 在Mapping中不需要指定 Type信息, 因为7.0之后只有_doc Type 当我们去创建一个

    2024年01月21日
    浏览(32)
  • ELK(Elasticsearch、Kibana、Logstash)以及向ES导入mysql数据库数据或CSV文件数据,创建索引和可视化数据

    地址:Past Releases of Elastic Stack Software | Elastic 在Products和version处分别选择需要下载的产品和版本,E(elasticsearch)L(logstash)K(kibana)三者版本必须相同 将下载好的elk分别解压到相同路径下 本文中elasticsearch=E=ES=es;L=logstash;K=kibana 一般情况下使用默认配置即可,下面对我的

    2024年02月15日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包