Table of Contents
Two ways to operate Elasticsearch with Python
Mysql and Elasticsearch synchronize data
Use of haystack
Redis supplement
Home Database Mysql Tutorial How Python operates ES and how to synchronize data with Mysql

How Python operates ES and how to synchronize data with Mysql

Jun 01, 2023 pm 09:49 PM
mysql python es

Two ways to operate Elasticsearch with Python

# 官方提供的:Elasticsearch
# pip install elasticsearch
# GUI:pyhon能做图形化界面编程吗?
	-Tkinter
  -pyqt
# 使用(查询是重点)
# pip3 install elasticsearch
https://github.com/elastic/elasticsearch-py
from elasticsearch import Elasticsearch
obj = Elasticsearch(['127.0.0.1:9200','192.168.1.1:9200','192.168.1.2:9200'],)
# 创建索引(Index)
# body:用来干什么?mapping:{},setting:{}
# result = obj.indices.create(index='user',ignore=400)
# print(result)
# 删除索引
# result = obj.indices.delete(index='user', ignore=[400, 404])
# 插入和查询数据(文档的增删查改),是最重要
# 插入数据
# POST news/politics/1
# {'userid': '1', 'username': 'lqz','password':'123'}
# data = {'userid': '1', 'username': 'lqz','password':'123'}
# result = obj.create(index='news', doc_type='politics', id=1, body=data)
# print(result)
# 更新数据
'''
不用doc包裹会报错
ActionRequestValidationException[Validation Failed: 1: script or doc is missing
'''
# data ={'doc':{'userid': '1', 'username': 'lqz','password':'123ee','test':'test'}}
# result = obj.update(index='news', doc_type='politics', body=data, id=1)
# print(result)
# 删除数据
# result = obj.delete(index='news', doc_type='politics', id=1)
# 查询
# 查找所有文档
# query = {'query': {'match_all': {}}}
#  查找名字叫做jack的所有文档
# query = {'query': {'match': {'desc': '娇憨可爱'}}}
# query = {'query': {'term': {'from': 'sheng'}}}
query = {'query': {'term': {'name': '娘子'}}}
# term和match的区别
# term是短语查询,不会对term的东西进行分词
# match 会多match的东西进行分词,再去查询
# 查找年龄大于11的所有文档
# allDoc = obj.search(index='lqz', doc_type='doc', body=query)
allDoc = obj.search(index='lqz', doc_type='doc', body=query)
print(allDoc)
import json
print(json.dumps(allDoc))
# print(allDoc['hits']['hits'][0]['_source'])
# 如何集成到django项目中:创建索引,提前创建好就行了
# 插入数据,查询数据,修改数据
# query = {'query': {'term': {'name': '娘子'}}}
# allDoc = obj.search(index='lqz', doc_type='doc', body=query)
# json格式直接返回
# saas :软件即服务,不是用人家服务,而是写服务给别人用----》正常的开发
# 舆情监测系统:(爬虫)
# 只监控微博---》宜家:微博,百度贴吧,上市公司
# 公安:负面的,---》追踪到哪个用户发的---》找上门了
# qq群,微信群----》舆情监控(第三方做不了,腾讯出的舆情监控,第三方机构跟腾讯合作,腾讯提供接口,第三方公司做)
# 平台开发出来,别人买服务---》买一年的微博关键字监控
Copy after login

ERP: corporate finance, supply chain

A large company, Kingdee, UFIDA, has developed software----》Your company itself Buy a server ---》The software runs on your server
saas model: The company buys services, 10 years of service----》Account and password---》Log in and you can operate ---》If there is a problem, contact UFIDA ---》The server is at someone else's place---》Government cloud, various clouds---all things go to the cloud

---Things the government spends money to buy---》Does UFIDA dare to leak it?
---Future cloud computing---》Can only access the Internet---》Computer computing power is limited---》Buy services on the cloud---》Compute 1. . . 100 ---》Buy the computing service and get the results directly

# 第二种使用方式
# https://github.com/elastic/elasticsearch-dsl-py
# pip3 install elasticsearch-dsl
from datetime import datetime
from elasticsearch_dsl import Document, Date, Nested, Boolean,analyzer, InnerDoc, Completion, Keyword, Text,Integer
from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=["localhost"])
class Article(Document):
    title = Text(analyzer='ik_max_word', search_analyzer="ik_max_word", fields={'title': Keyword()})
    author = Text()
    class Index:
        name = 'myindex'  # 索引名
    def save(self, ** kwargs):
        return super(Article, self).save(** kwargs)
if __name__ == '__main__':
    # Article.init()  # 创建映射
    # 保存数据
    # article = Article()
    # article.title = "测试数据"
    # article.author = "egon"
    # article.save()  # 数据就保存了
    #查询数据
    # s=Article.search()
    # s = s.filter('match', title="测试")
    # results = s.execute()
    # # 类比queryset对象,列表中一个个对象
    # # es中叫Response,当成一个列表,列表中放一个个对象
    # print(results)
    #删除数据
    # s = Article.search()
    # s = s.filter('match', title="测试").delete()
    #修改数据
    s = Article().search()
    s = s.filter('match', title="测试")
    results = s.execute()
    print(results[0])
    results[0].title="xxx"
    results[0].save()
    # 其他操作,参见文档
Copy after login

Mysql and Elasticsearch synchronize data

# 只要article表插入一条数据,就自动同步到es中
# 第一种方案:
	-每当aritcle表插入一条数据(视图类中,Article.objects.create(),update)
  -往es中插入一条
  -缺陷:代码耦合度高,改好多地方
# 第二种方案:
	-重写create方法,重写update方法
  -缺陷:同步操作---》es中插入必须返回结果才能继续往下走
# 第三种方案:
	-用celery,做异步
  -缺陷:引入celery,还得有消息队列。。。
# 第四种方案:(用的最多)
	-重写create方法,重写update方法,用信号存入,异步操作
  -缺陷:有代码侵入
# 第五种方案:(项目不写代码,自动同步),第三方开源的插件
	-https://github.com/siddontang/go-mysql-elasticsearch----go写
  -你可以用python重写一个,放到git上给别人用(读了mysql的日志)
  -跟平台无关,跟语言无关
  -如何使用:
  	-源码下载---》交叉编译---》可执行文件--》运行起来--》配置文件配好,就完事了
    # 配置文件
    [[source]]
    schema = "数据库名"
    tables = ["article"]
    [[rule]]
    schema = "数据库名"
    table = "表明"
    index = "索引名"
    type = "类型名"
  # 缺陷:
  	-es跟mysql同步时,不希望把表所有字段都同步,mysql的多个表对着es的一个类型
  # 话术升级:
  	-一开始同步
    -用了开源插件(读取mysql日志,连接上es,进行同步)
    -用信号自己写的
    -再高端:仿着他的逻辑,用python自己写的,----》(把这个东西开源出来)
Copy after login

Use of haystack

  • django A third-party module---》What are the third-party Django modules you have used?

  • Can realize full-text search on django

  • Equivalent to ORM--》Docking es, solr, whoosh

  • https://www.yisu.com/article/218631.htm

  • does not support es, version 6 or above

  • haystack Elasticsearch implements full-text retrieval

  • es native operation: ELlasticsearch Elasticsearch-dsl

Redis supplement

#1  只有5种数据结构:
	-多种数据结构:字符串,hash,列表,集合,有序集合
#2  单线程,速度为什么这么快?
  -本质还是因为是内存数据库
  -epoll模型(io多路复用)
  -单线程,没有线程,进程间的通信
#3 linux上 安装redis#下载
  https://redis.io/download/
  #解压
  tar -xzf redis-5.0.7.tar.gz
  #建立软连接
  ln -s redis-5.0.7 redis
  cd redis
  make&&make install
  # bin路径下几个命令:redis-cli,redis-server,redis-sentinel
  # 在任意位置能够执行redis-server 如何做?配置环境变量
#4  启动redis的三种方式
  	-方式一:(一般不用,没有配置文件)
    	-redis-server
    -方式二:(用的也很少)
    	redis-serve --port 6380
    -方式三:(都用这种,配置文件)
    	daemonize yes #是否以守护进程启动
      pidfile /var/run/redis.pid   #进程号的位置,删除
      port 6379    #端口号
      dir "/opt/soft/redis/data"  #工作目录
      logfile 6379.log #日志位置  
      # 启动:redis-server redis.conf1
#5 客户端连接
  redis-cli -h 127.0.0.1 -p 6379
#6 使用场景
  -看md文档
Copy after login

The above is the detailed content of How Python operates ES and how to synchronize data with Mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to use Debian Apache logs to improve website performance How to use Debian Apache logs to improve website performance Apr 12, 2025 pm 11:36 PM

This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

The role of Debian Sniffer in DDoS attack detection The role of Debian Sniffer in DDoS attack detection Apr 12, 2025 pm 10:42 PM

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

See all articles