pi-2r
pi-2r

Reputation: 1279

"exceptions.TypeError: list indices must be integers not str" in python with Elasticsearch

I try to obtain the id of document with my function, but I've got this error:

    var = data['hits']['hits']['_id']
exceptions.TypeError: list indices must be integers, not str

my little function:

def FoundIdDocument(reference):
    print "foundiddocument"
    url = BuildUrl()+'_search?q=name:"'+reference.replace(' ','%20')+'"'
    req = urllib2.Request(url)
    out = urllib2.urlopen(req)
    data = out.read()
    print data
    # returned data is JSON            
    data = json.loads(data)
    # total number of results    
    var = data['hits']['hits']['_id']
    print var

Upvotes: 1

Views: 2042

Answers (1)

hughdbrown
hughdbrown

Reputation: 49033

Print the keys and figure it out:

print data.keys()
# Does it have 'hits'? If yes, do this:
print data['hits'].keys()
# Does it have 'hits'? If yes, do this:
print data['hits']['hits'].keys()
# You should have hit an error by this point

Upvotes: 4

Related Questions