Home  >  Article  >  Database  >  How Python operates ES and how to synchronize data with Mysql

How Python operates ES and how to synchronize data with Mysql

王林
王林forward
2023-06-01 21:49:101365browse

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群,微信群----》舆情监控(第三方做不了,腾讯出的舆情监控,第三方机构跟腾讯合作,腾讯提供接口,第三方公司做)
# 平台开发出来,别人买服务---》买一年的微博关键字监控

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()
    # 其他操作,参见文档

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自己写的,----》(把这个东西开源出来)

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文档

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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete