Skip to content

Instantly share code, notes, and snippets.

@zubairalam
Forked from bonzanini/create_index.sh
Created October 13, 2015 09:07
Show Gist options
  • Save zubairalam/08361e37ea6b321cc0ff to your computer and use it in GitHub Desktop.
Save zubairalam/08361e37ea6b321cc0ff 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