Skip to content

Instantly share code, notes, and snippets.

@charlesmims
Last active August 29, 2015 14:26
Show Gist options
  • Save charlesmims/0590c86dcce4c5be6272 to your computer and use it in GitHub Desktop.
Save charlesmims/0590c86dcce4c5be6272 to your computer and use it in GitHub Desktop.
def kv_diff(A, B, whitelist=[]):
'''
Function can be used on elasticsearch mappings to identify variations.
Returns a diff.
Eg:
template = requests.get(es_url + '/_template/mytemplate', auth=(es_user,es_pass)).json()['projects']['mappings']
mapping = requests.get(es_url + '/foo/_mapping' % project_id, auth=(es_user,es_pass)).json()['foo']['mappings']
kv_diff(template, mapping)
'''
try:
retval = {}
A_keys = A.keys()
B_keys = B.keys()
A_set = set(A_keys)
B_set = set(B_keys)
diff = A_set.symmetric_difference(B_set)
intersection = A_set.intersection(B_set)
intersection_copy = intersection.copy()
for item in set(whitelist):
if item in diff:
diff.remove(item)
if item in intersection:
intersection_copy.remove(item)
intersection = intersection_copy
if diff:
for item in diff:
if item in A_keys:
retval['A'] = retval.get('A', {})
retval['A'][item] = A[item]
if item in B_keys:
retval['B'] = retval.get('B', {})
retval['B'][item] = B[item]
for key in intersection:
kvdiff = kv_diff(A[key], B[key], whitelist)
if kvdiff:
retval[key] = kvdiff
return retval
except AttributeError:
if A == B:
return {}
else:
return {'A': A, 'B': B}
@charlesmims
Copy link
Author

feedback appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment