Skip to content

Instantly share code, notes, and snippets.

@ayang
Last active August 29, 2015 14:16
Show Gist options
  • Save ayang/c72c67651e47e455f710 to your computer and use it in GitHub Desktop.
Save ayang/c72c67651e47e455f710 to your computer and use it in GitHub Desktop.
Run a elasticsearch query from a json file begin with a headline like that in the "The Definitive Guide"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
parse a file with a headline and json content like this:
GET /index/type/_search?pretty
{
"query": {
"match": {
"title": "hello world"
}
}
}
to make a elasticsearch restful query.
multiple queries can in one query file, splited by blank line.
"""
import sys
import json
import requests
import click
def print_json(content, pretty=False):
if not pretty:
print content
else:
data = json.loads(content)
content_pretty = json.dumps(data, indent=2)
print content_pretty
def parse_and_query(query_file, pretty=False):
while True:
headline = query_file.readline()
if not headline:
return False
if headline.startswith('#'):
continue
break
try:
method, url = headline.split()
except:
print 'Bad headline, exit!'
return False
if method not in ('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'):
print 'Wrong method: %s' % method
return False
if url.startswith('/'):
url = 'http://localhost:9200%s' % url
print '-' * 80
print method, url
lines = []
while True:
line = query_file.readline()
if not line or not line.strip():
break
if headline.lstrip().startswith('#'):
continue
lines.append(line)
data = ''.join(lines)
resp = requests.request(method, url, data=data)
if resp.ok:
print 'OK', resp.status_code
print_json(resp.content, pretty)
else:
print 'FAIL', resp.status_code
print_json(resp.content, pretty)
return True
@click.command()
@click.option('-p', '--pretty', is_flag=True, help='Pretty output json')
@click.argument('filenames', nargs=-1)
def main(pretty, filenames):
for filename in filenames:
with open(filename) as f:
while True:
ret = parse_and_query(f, pretty=pretty)
if not ret:
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment