2017-02-12 68 views
0

在我的Java應用程序中,我需要在ElasticSearch中存儲JSON文檔。我想防止ES中的文檔重複,所以我將計算基於JSON對象/字符串的某種id(鍵),並在ES中建立索引時將其用作此文檔的自己的ID。不幸的是,我沒有任何這個JSON中的自然鍵的候選人,所以應該考慮到這個鍵生成的整個JSON對象/字符串。在Elasticsearch的JSON文檔上創建一個id(key)基礎

這是JSON文件的一個例子:

{ 
    "filterQueries":[ 
     { 
     "type":"LessOrEqualQuery", 
     "characteristicId":630, 
     "value":799621200000, 
     "operator":"<=" 
     } 
    ], 
    "sortCriteriaIds":[ 
     566, 
     572 
    ], 
    "sortWeightCriteriaDirection":"DESC", 
    "sortTotalVotesCriteriaDirection":null, 
    "sortCriteriaCoefficients":{ 
     "572":20.0 
    }, 
    "sortCharacteristicId":631, 
    "sortCharacteristicDirection":"DESC", 
    "sortDecisionPropertyName":"createDate", 
    "sortDecisionPropertyDirection":"DESC", 
    "excludeChildDecisionIds":null, 
    "includeChildDecisionIds":null, 
    "pageNumber":0, 
    "pageSize":100 
} 

什麼是計算基於Java中JSON對象/字符串此鍵的最佳方式?對我來說,表現是一個非常重要的標準。

+0

如果JSON是一樣的,但性能鍵順序是不相一致,應該產生的關鍵是一樣的嗎? – laser

+0

理想情況是,但不是強制性的。我會盡量保持自己的訂單 – alexanoid

+1

,那麼你可以簡單地stringify,然後sha256(字符串)?或者更小的尺寸任何哈希...取決於哈希大小,碰撞概率將會不同。 – laser

回答

1

如果速度很關心。您可以使用異或操作(對於任何大小几乎都是CRC32)。

僞代碼:

input_string = Stringify(json) 
result = 0; 
for(each chunk of size K from input_string){ 
    result = result XOR chunk; 
} 
return result 
+0

我認爲crc32應該爲我工作,謝謝! \t'public static long crc32(String input){ \t \t byte [] bytes = input.getBytes(); \t \t校驗和checksum = new CRC32(); \t \t checksum.update(bytes,0,bytes.length); \t \t return checksum.getValue(); \t}' – alexanoid

相關問題