JSONフィールドの索引付け
JSONフィールドに対して索引を作成できます。索引を作成するには、索引付けするJSONフィールドのデータ型を定義する必要があることを除き、他の索引と同様に指定します。
索引付けできるJSONフィールドのデータ型にはいくつかの制限があることに注意してください。詳細は、JSON索引を参照してください。
索引を作成するには、まず表を作成します。
CREATE Table JSONPersons (
id INTEGER,
person JSON,
PRIMARY KEY (id)
)
索引を作成するには、ドット表記法を使用して索引付けするJSONフィールドを指定する必要があります。次のような表の行があるとします。
"id":1,
"person" : {
"firstname":"David",
"lastname":"Morrison",
"age":25,
"income":100000,
"lastLogin" : "2016-10-29T18:43:59.8319",
"address":{"street":"150 Route 2",
"city":"Antioch",
"state":"TN",
"zipcode" : 37013,
"phones":[{"type":"home", "areacode":423,
"number":8634379}]
},
"connections":[2, 3],
"expenses":{"food":1000, "gas":180}
}
表をストアに追加した後、次のようなJSONフィールドの1つに索引を作成できます。
CREATE INDEX idx_json_income on JSONPersons (person.income AS integer)
JSON索引を使用してデータを取得するには、JSONフィールドを識別するためにドット表記法を使用して索引キーを作成します。次に、Store.index_iterator()
を使用して、索引キーに一致する表の行にアクセスします。たとえば、person.income
フィールドが100000の行をすべて取得するには、次のようにします。
def display_row(row):
try:
print "Retrieved row:"
print "\tid: %s" % row['id']
print "\tperson: %s" % row['person']
except KeyError, ke:
logging.error("Row display failed. Bad key: %s" % ke.message)
def read_store(store):
store.refresh_tables()
try:
key_d = {"person.income" : 100000}
row_list = store.index_iterator("JSONPersons",
"idx_json_income",
key_d,
False)
if not row_list:
logging.debug("Table retrieval failed")
else:
logging.debug("Table retrieval succeeded.")
for r in row_list:
display_row(r)
except IllegalArgumentException, iae:
logging.error("Table retrieval failed.")
logging.error(iae.message)