Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions server/services/datacommons.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import collections
import json
import logging
import math
from typing import Dict, List

from flask import current_app
Expand Down Expand Up @@ -459,18 +460,25 @@ def _get_all_values(resp, dcid, prop, key='dcid'):


def _get_best_type(types_list):
"""Selects the best type from a list of types based on PLACE_TYPE_RANK."""
"""Selects the most specific place type from a list of types.

Prioritizes types with a lower non-zero rank in PLACE_TYPE_RANK (e.g. City
over State over Place), prioritizes standard names over 'AdministrativeArea'
names, and puts unrecognized types last.
"""
if not types_list:
return ''

# Sort types by rank (highest rank first)
# Prefer known types over unknown types.
# Within known types, prefer smaller rank (more specific, e.g. City (30) < State (80) < Place (150))
# If ranks are tied, prefer types that don't start with 'AdministrativeArea'
def sort_key(t):
rank = PLACE_TYPE_RANK.get(t, 0)
raw_rank = PLACE_TYPE_RANK.get(t, 0)
rank = raw_rank if raw_rank > 0 else math.inf
is_admin = 1 if t.startswith('AdministrativeArea') else 0
return (rank, -is_admin)
return (rank, is_admin)

return sorted(types_list, key=sort_key, reverse=True)[0]
return min(types_list, key=sort_key)


def get_place_info(dcids: List[str]) -> Dict:
Expand Down
8 changes: 8 additions & 0 deletions server/tests/migration_verification_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ def side_effect(url, data, api_key=None, log_extreme_calls=False):
"typeOf": {
"nodes": [{
"dcid": "Country"
}, {
"dcid": "Place"
}, {
"dcid": "SomeCustomType"
}]
}
}
Expand All @@ -55,6 +59,10 @@ def side_effect(url, data, api_key=None, log_extreme_calls=False):
"typeOf": {
"nodes": [{
"dcid": "State"
}, {
"dcid": "Place"
}, {
"dcid": "SomeOtherCustomType"
}]
}
}
Expand Down
Loading