2013-10-09 123 views
1

我正在使用elasticsearch將查詢發佈到json中,並且應該按照標準順序進行,否則結果將會出錯。問題是python正在改變我的json排序。我原來的json查詢是。在python映射對象中排序json

x= { 
    "query": { 
    "filtered": { 
     "query": { 
     "query_string": { 
      "query": "*a*" 
     } 
     }, 
     "filter": { 
     "and": { 
      "filters": [ 
      { 
       "term": { 
       "city": "london" 
       } 
      }, 
      { 
       "term": { 
       "industry.industry_not_analyed": "oil" 
       } 
      } 
      ] 
     } 
     } 
    } 
    }, 
    "facets": { 
    "industry": { 
     "terms": { 
     "field": "industry.industry_not_analyed" 
     } 
    }, 
    "city": { 
     "terms": { 
     "field": "city.city_not_analyzed" 
     } 
    } 
    } 
} 

但生成的python對象如下。

{ 
    'query': { 
    'filtered': { 
     'filter': { 
     'and': { 
      'filters': [ 
      { 
       'term': { 
       'city': 'london' 
       } 
      }, 
      { 
       'term': { 
       'industry.industry_not_analyed': 'oil' 
       } 
      } 
      ] 
     } 
     }, 
     'query': { 
     'query_string': { 
      'query': '*a*' 
     } 
     } 
    } 
    }, 
    'facets': { 
    'city': { 
     'terms': { 
     'field': 'city.city_not_analyzed' 
     } 
    }, 
    'industry': { 
     'terms': { 
     'field': 'industry.industry_not_analyed' 
     } 
    } 
    } 
} 

結果與我所需要的不同,我該如何解決這個問題。

+0

哪個版本的Python? –

+0

我的Python版本是2.7.5 – Sar009

+0

[Python字典,保持鍵/值的順序與聲明相同]的可能重複(http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in聲明同樣的順序) –

回答

3

使用OrderedDict()而不是{}。請注意,您不能簡單地使用OrderedDict(query=...),因爲這會在後臺創建無序的字典。使用此代碼來代替:

x = OrderedDict() 
x['query'] = OrderedDict() 
... 

我建議實現此建設者:

x = Query().filtered().query_string("*a*").and().... 
+0

你能幫我一下嗎?如何使用OrderedDict()編寫完整的查詢() – Sar009

+0

爲此編寫一個單元測試,並逐步構建查詢,直到輸出完全按照你的需要。 –

+0

我感謝你的興趣和你的負擔,但我無法弄清楚如何編寫查詢 A = { \t「一」:「一個」, \t「B」:「B」 } 打印一個 b = {} b [ '一'] = 「A」 b [ 'b'] = 「b」 的 印片b C = collections.OrderedDict() C [ '一'] =」 a「 c ['b'] =」b「 print c 輸出: {'a':'a','b':'b'} ('''''','b':'b'} OrderedDict寫出查詢的方式 – Sar009