Skip to content

Instantly share code, notes, and snippets.

@saviour123
Forked from bonzanini/create_index.sh
Created June 1, 2017 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saviour123/3e7f89f60e983deb7d282659ff6eaaad to your computer and use it in GitHub Desktop.
Save saviour123/3e7f89f60e983deb7d282659ff6eaaad to your computer and use it in GitHub Desktop.
Elasticsearch/Python test
curl -XPOST http://localhost:9200/test/articles/1 -d '{
"content": "The quick brown fox"
}'
curl -XPOST http://localhost:9200/test/articles/2 -d '{
"content": "What does the fox say?"
}'
curl -XPOST http://localhost:9200/test/articles/3 -d '{
"content": "The quick brown fox jumped over the lazy dog"
}'
curl -XPOST http://localhost:9200/test/articles/4 -d '{
"content": "The quick lazy brown fox did not jump."
}'
from elasticsearch import Elasticsearch
if __name__ == '__main__':
es = Elasticsearch()
res = es.search(index="test", doc_type="articles", body={"query": {"match": {"content": "fox"}}})
print("%d documents found:" % res['hits']['total'])
for doc in res['hits']['hits']:
print("%s) %s" % (doc['_id'], doc['_source']['content']))
#es.create(index="test", doc_type="articles", body={"content": "One more fox"})
"""
Simple example of querying Elasticsearch creating REST requests
"""
import requests
import json
def search(uri, term):
"""Simple Elasticsearch Query"""
query = json.dumps({
"query": {
"match": {
"content": term
}
}
})
response = requests.get(uri, data=query)
results = json.loads(response.text)
return results
def format_results(results):
"""Print results nicely:
doc_id) content
"""
data = [doc for doc in results['hits']['hits']]
for doc in data:
print("%s) %s" % (doc['_id'], doc['_source']['content']))
def create_doc(uri, doc_data={}):
"""Create new document."""
query = json.dumps(doc_data)
response = requests.post(uri, data=query)
print(response)
if __name__ == '__main__':
uri_search = 'http://localhost:9200/test/articles/_search'
uri_create = 'http://localhost:9200/test/articles/'
results = search(uri_search, "fox")
format_results(results)
#create_doc(uri_create, {"content": "The fox!"})
#results = search(uri_search, "fox")
#format_results(results)
curl -XPOST http://localhost:9200/test/articles/_search?pretty=true -d '{
"query": {
"match": {
"content": "dog"
}
}
}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment