2014-07-22 2 views
1

와 파이썬에서 "exceptions.TypeError 목록 지수는 정수 str에하지해야합니다",하지만 난이 오류가있어 :: 내 기능으로 문서의 ID를 얻으려고 Elasticsearch

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

내 작은 기능을 :

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 
+0

하나는 사전이 실제로 목록입니다. 그것은'data [ 'hits']'일 수 있습니다. 그것은'data [ 'hits'] [ 'hits']'일 수 있습니다. 그것은'data [ 'hits'] [ 'hits'] [ '_ id']'일 수 있습니다. – hughdbrown

+0

이 솔루션을 찾았습니다 : 데이터 [ 'hits'] [ 'hits']의 색인 용 : return index [ '_ id'] –

+0

위 해결책을 모르겠습니다. 루프는 한 번만 실행됩니다. 차이점은'data [ 'hits'] [ 'hits']'가 비어 있고 루프가 실행되지 않거나'data [ 'hits'] [ 'hits']'가 키'_id를 가진 사전을 가지고있을 때 발생합니다 '. 그러나 어떤 경우에도 데이터 구조 중 하나가 사전이 아닌 목록 인 경우에는 도움이되지 않습니다. – hughdbrown

답변

4

인쇄 키와 그것을 알아낼 : 당신이 생각하는 것들의

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 
+0

이것은 * value *가 목록 인 것을 보여주지 않을 것입니다; 목록에는'.keys()'메소드가 없기 때문에 속성 에러가 발생합니다. –

+0

충분히 공정합니다. 메서드는 소리가 있지만 주석이 잘못되었습니다. – hughdbrown

+0

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/_the_search_api.html을 참조하십시오. 'data ['hits '] ['hits ']'는 목록입니다. –

관련 문제