增删改
先创建模型类
class JobDetail():
def __init__(self, id, area, cmp, edu, exp, title, job_type, pv, jd, salary):
self.id = id
self.area = area
self.cmp = cmp
self.edu = edu
self.exp = exp
self.title = title
self.job_type = job_type
self.pv = pv
self.jd = jd
self.salary = salary
def get_jobdetail(self):
return {'id':self.id, 'area':self.area, 'cmp':self.cmp, 'edu':self.edu, 'exp':self.exp, 'title':self.title, 'job_type':self.job_type, 'pv':self.pv, 'jd':self.jd, 'salary':self.salary}
1、增(index)
from elasticsearch import Elasticsearch
from jobdetail import JobDetail
if __name__ == '__main__':
es = Elasticsearch(hosts='192.168.xx.xxx:9200')
# 验证ES对象是否创建成功
print(es)
# 创建对象,并初始化数据
jd = JobDetail(1, '海淀区后厂村', '百度', '本科', '不限', '大数据开发工程师', '全职', 1000, '负责数仓开发', '15k')
# index,ID,document
response = es.index(index='job_idx',id=2,document=jd.get_jobdetail())
print(response)
es.close()
改
response = es.update(index='job_idx',id=2,doc={'edu':'不限'})
删
response = es.delete(index='job_idx',id=2)
查
response=es.search(index='job_idx',query={
'match':{
'jd':'销售'
}
})
print(response)
for hits in response['hits']['hits']:
print(hits['_source'])
es.close()
在多个字段中查
response=es.search(index='job_idx',query={
'multi_match':{
'query':'淘宝店长',
'fields':['title','jd']
}
})
for hits in response['hits']['hits']:
print(hits['_source'])
es.close()
高亮
response = es.search(index='job_idx',query={
"multi_match": {
"query": "淘宝店长",
"fields": ["title", "jd"]
}
},from_=0,size=5,highlight={'fields':{'jd':{},'title':{}}})
# 调用search方法之后, 会产生一个响应
# print(response['hits']['hits'])
for hit in response['hits']['hits']:
hit['_source']['jd'] = hit['highlight']['jd']
hit['_source']['title'] = hit['highlight']['title']
print(hit['_source'])
es.close()