1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import pymysql from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk
cnx = pymysql.connect(user='root', password='YDXcgyz123.', host='localhost', database='search') cursor = cnx.cursor() print('连接mysql')
query = "SELECT * FROM search_policy" cursor.execute(query) res0 = cursor.fetchall()
es = Elasticsearch(hosts=[ ''])
index_name = 'policy_title_suggest_index' mapping = { "mappings": { "properties": { "policy_title_suggest": { "type": "completion", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word", "preserve_position_increments": False, "preserve_separators": False, "max_input_length": 50, } } } } es.indices.delete(index='policy_title_suggest_index', ignore=[400, 404])
es.indices.create(index=index_name, body=mapping)
new_docs = [] count = 0 for row in res0: if row[1]: doc = { "_index": index_name, "_id": row[0], "policy_title_suggest": { "input": [row[1]], "weight": 1, } } new_docs.append(doc) count += 1 if count % 5000 == 0: bulk(es, new_docs) new_docs = []
if new_docs: bulk(es, new_docs)
es.indices.refresh(index=index_name)
|