python自动生成pg数据库表对应的es索引

项目需要用到Es进行查询。手动创建Es索引太麻烦,写了个脚本。

首先需要安装两个库

复制代码
pip install psycopg2

我使用的es版本是7.10的安装对应版本的elasticsearch库

复制代码
pip install elasticsearch==7

以下是生成索引代码

复制代码
import psycopg2  # 导入psycopg2驱动程序
from elasticsearch import Elasticsearch

# 连接到Elasticsearch
es = Elasticsearch(["http://192.168.1.2:9210"])
index_mapping = {
    'mappings': {
        'properties': {}
    }
}


def getcolumns(table):
    # 创建数据库连接
    cnx = psycopg2.connect(
        host='192.168.1.26',
        port='5432',
        database='test',
        user='postgres',
        password='******'
    )

    # 创建游标
    cursor = cnx.cursor()
    # 执行查询语句
    query = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table}'"
    cursor.execute(query)

    # 获取结果
    result = cursor.fetchall()

    # 关闭游标和连接
    cursor.close()
    return result


def get_es_type(data_type):
    if data_type == 'integer':
        return 'integer'
    elif data_type == 'bigint':
        return 'long'
    elif data_type == 'numeric':
        return 'float'
    elif data_type == 'character varying' or data_type == 'text':
        return 'text'
    elif data_type == 'boolean':
        return 'boolean'
    elif data_type == 'timestamp with time zone' or data_type == 'timestamp without time zone':
        return 'date'
    elif data_type == 'bytea':
        return 'binary'
    else:
        return 'keyword'  # 默认使用keyword类型


# 创建Es索引
def create_index(table_name, index_name):
    result = getcolumns(table_name)

    # 添加字段映射
    for column_name, data_type in result:
        es_type = get_es_type(data_type)
        index_mapping['mappings']['properties'][column_name] = {'type': es_type}
        if es_type == 'text' or es_type == 'keyword':
            index_mapping['mappings']['properties'][column_name] = {
                'type': es_type,
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
    # 使用indices.exists()方法判断Index是否存在
    if not es.indices.exists(index=index_name):
        es.indices.create(index=index_name, body=index_mapping)
        print(f'索引{index_name}创建成功。')
    else:
        print(f'索引{index_name}已存在,无需创建。')


# 需要创建索引的表
indexlist = [
    {
        'table_name': 'pg_table1',
        'index_name': 'es_index1'
    },
    {
        'table_name': 'pg_table2',
        'index_name': 'es_index2'
    },
    {
        'table_name': 'pg_table3',
        'index_name': 'es_index3'
    },
    {
        'table_name': 'pg_table4',
        'index_name': 'es_index4'
    }
]

for indexinfo in indexlist:
    table_name = indexinfo['table_name']
    index_name = indexinfo['index_name']
    create_index(table_name, index_name)
相关推荐
MUTA️几秒前
pycharm中本地Docker添加解释器
ide·python·pycharm
Code季风8 分钟前
SQL关键字快速入门:HAVING 分组后的条件过滤
数据库·sql·mysql
想要成为计算机高手37 分钟前
4. isaac sim4.2 教程-Core API-Hello robot
人工智能·python·机器人·英伟达·isaac sim·仿真环境
程序猿ZhangSir40 分钟前
Redis 缓存进阶篇,缓存真实数据和缓存文件指针最佳实现?如何选择?
数据库·redis·缓存
yjb.gz42 分钟前
Oracle函数JSON_TABLE使用
数据库·oracle·json
Dubhehug1 小时前
4.B树和B+树的区别?为什么MySQL选择B+树作为索引?
数据库·b树·mysql·面试·b+树
陈敬雷-充电了么-CEO兼CTO1 小时前
复杂任务攻坚:多模态大模型推理技术从 CoT 数据到 RL 优化的突破之路
人工智能·python·神经网络·自然语言处理·chatgpt·aigc·智能体
YOLO大师2 小时前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
linux修理工2 小时前
n1 armbian 安装桌面环境并启用xrdp远程登录
linux·服务器·数据库
xiao5kou4chang6kai42 小时前
【Python-GEE】如何利用Landsat时间序列影像通过调和回归方法提取农作物特征并进行分类
python·gee·森林监测·洪涝灾害·干旱评估·植被变化