PUT json data to Elasticsearch cluster Python
Question: I'm trying to PUT data to an Elasticsearch server. I can manually PUT the
data, but I can't seem to automate it.

    
    
    jsonValue = json.dumps(data).encode('utf8')
    
    req = urllib2.Request("http://[Elastic IP Address]/cities", jsonValue, {'Content-Type': 'application/json'})
    req.get_method = lambda: 'PUT'
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()
    

The error that I am getting:

    
    
    Traceback (most recent call last):
      File "import_elastic.py", line 27, in <module>
        f = urllib2.urlopen(req)
      File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
        return opener.open(url, data, timeout)
      File "/usr/lib/python2.7/urllib2.py", line 437, in open
        response = meth(req, response)
      File "/usr/lib/python2.7/urllib2.py", line 550, in http_response
        'http', request, response, code, msg, hdrs)
      File "/usr/lib/python2.7/urllib2.py", line 475, in error
        return self._call_chain(*args)
      File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
        result = func(*args)
      File "/usr/lib/python2.7/urllib2.py", line 558, in http_error_default
        raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
    urllib2.HTTPError: HTTP Error 400: Bad Request
    

The first value that I am PUTing:

    
    
    {"name": "Tia Juana River", "country": "US", "alternate": "Rio Tiajuana,Rio Tijuana,R\u00edo Tijuana,Tia Juana River", "long": "-117.12865", "lat": "32.55668", "timezone": "America/Los_Angeles", "id": "3981608", "population": "0"}
    


Answer: You need to put the type name too

    
    
    http://[Elastic IP Address]/cities/city
    

The above URL should work. Between there is a Elasticsearch client for python
, feel free to try out that too.

