文檔:http://elasticsearch-py.readthedocs.io/en/master/html
Elasticsearch官方API文檔:https://www.elastic.co/guide/en/elasticsearch/reference/current/search.htmlpython
兩種方式現實Elasticsearch API操做json
方式一:安裝elasticsearch模塊,經過它操做Elasticsearch,代碼示例以下app
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
|
"""
pip install elasticsearch
"""
from
elasticsearch
import
Elasticsearch
class
ElasticSearchClass(
object
):
def
__init__(
self
, host, port, user, passwrod):
self
.host
=
host
self
.port
=
port
self
.user
=
user
self
.password
=
passwrod
self
.connect()
def
connect(
self
):
self
.es
=
Elasticsearch(hosts
=
[{
'host'
:
self
.host,
'port'
:
self
.port}],
http_auth
=
(
self
.user,
self
.password ))
def
count(
self
, indexname):
"""
:param indexname:
:return: 統計index總數
"""
return
self
.es.count(index
=
indexname)
def
delete(
self
, indexname, doc_type,
id
):
"""
:param indexname:
:param doc_type:
:param id:
:return: 刪除index中具體的一條
"""
self
.es.delete(index
=
indexname, doc_type
=
doc_type,
id
=
id
)
def
get(
self
, indexname,
id
):
return
self
.es.get(index
=
indexname,
id
=
id
)
def
search(
self
, indexname, size
=
10
):
try
:
return
self
.es.search(index
=
indexname, size
=
size, sort
=
"@timestamp:desc"
)
except
Exception as err:
print
(err)
|
方式二:安裝requests模塊,經過GET、POST方式操做Elasticsearchelasticsearch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class
RequestsElasticSearchClass(
object
):
def
__init__(
self
, host, port, user, passwrod):
self
.url
=
'http://'
+
host
+
':'
+
str
(port)
basicpwd
=
base64.b64encode((user
+
':'
+
passwrod).encode(
'UTF-8'
))
self
.headers
=
{
"User-Agent"
:
"shhnwangjian"
,
"Content-Type"
:
"application/json"
,
"Authorization"
:
"Basic {}"
.
format
(basicpwd.decode(
'utf-8'
))}
def
search(
self
, indexname, size
=
10
):
gettdata
=
{
"sort"
:
"@timestamp:desc"
,
"size"
: size}
url
=
self
.url
+
'/'
+
indexname
+
'/_search'
ret
=
requests.get(url, headers
=
self
.headers, timeout
=
10
, params
=
gettdata)
print
(ret.text)
|
備註:python3.6.1版本ide