7

There are to libraries to do this pyes and pyelasticsearch. The pyelasticsearch website looks good, and pyes take an other approach but also is ok.

In the other hand this code works and it is very simple.

import urllib2 as urllib
import json
import pprint

query = {
    "from":0,
    "size":10,
    "query":{
        "field" : { 
            "name" : "david"
        }
    },
    "sort":[
        {"name":"asc"},
        {"lastName":"asc"}
    ]
}

query = json.dumps(query)
response = urllib.urlopen(
    'http://localhost:9200/users/users/_search',
    query
)

result = json.loads( response.read() )

pprint.pprint(result)

So I'm thinking about use the simple code instead of learn the tricks of the libraries.

3
  • this is fine ... although people typically use urllib2.urlopen ... I think it resolves some urllib issues... Commented Sep 26, 2012 at 16:12
  • @JoranBeasley, urllib2 is being used. Commented Sep 26, 2012 at 17:37
  • oh yeah... didnt notice earlier .. Commented Sep 26, 2012 at 17:52

2 Answers 2

7

There is nothing wrong with your approach of using the REST API to interface with ElasticSearch.

Pyes and the other libraries provide a wrapper around the REST API so that you can write Python code as oppose to building the JSON queries yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

Be aware that your code snippet as shown in your question won't work in Python 3. One has to encode the query string and also add a content header to your request. So in Python 3 do the following:

from urllib.request import urlopen, Request
import json
import pprint

query = {
    "from":0,
    "size":10,
    "query":{
        "field" : { 
            "name" : "david"
        }
    },
    "sort":[
        {"name":"asc"},
        {"lastName":"asc"}
    ]
}
# encode your json string
query = json.dumps(query).encode("utf-8")
# add a content-type header
request = Request('http://localhost:9200/users/users/_search', data=query, headers={'Content-Type': 'application/json'})
response = urlopen(request)
result = json.loads( response.read() )
pprint.pprint(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.