我想找到所有年份值以20开头的对象...所以我想搜索20 *,其中*是外卡。 我尝试了类似
的东西'match_phrase_prefix': { 'year': { 'query': '20*', 'max_expansions': 50}}
但我想这只适用于字符串。我如何为整数做这个?
编辑:我找到了一个解决方案......它不漂亮但是有效
year_query = '20'
if len(str(year_query)) < 4:
try:
low_year, high_year = extend_year(int(year_query))
filter_list.append({"range": {"year": {"gte": low_year, "lte": high_year}}})
except ValueError:
print "Not a valid input for year"
pass
else:
for year in year_query.split(','):
if '-' in year:
year_range = year.split('-')
high_year = year_range[1].strip()
if len(high_year) < 4:
low_year, high_year = extend_year(high_year)
try:
filter_list.append({"range" : {"year" : {"gte" : int(year_range[0].strip()),"lte" : int(high_year),"format": "yyyy"}}})
except ValueError:
print "Not a valid input for year"
pass
else:
try:
filter_list.append({ "match": {"year": int(year.strip()) }})
except ValueError:
print "Not a valid input for year"
pass
具有功能
def extend_year(input_year):
length = len(str(input_year))
if length == 4:
return input_year, 0
elif length == 3:
return input_year*10, int(str(input_year) + '9')
elif length == 2:
return input_year*100, int(str(input_year) + '99')
elif length == 1:
return input_year*1000, int(str(input_year) + '999')
elif length == 0:
return 0, 9999
else:
return input_year, 0
如果有人能提出更好的解决方案,请告诉我
答案 0 :(得分:3)
这应该有效
'range': { 'year': { 'gte': 2000, 'max_expansions': 50}}