我有一个城市名称字段,我从中获得价值(即随机格式化),例如“纽约”,“纽约”或“纽约”或“纽约”。
拥有该字段的值,我需要向用户显示以这种格式在其名称中具有该值的城市列表:
纽约 - 纽约市 - 10001
MN - 纽约米尔斯 - 56567
效率和性能很重要。我可以使用JavaScript或PHP来检索这些数据。
到目前为止,我已尝试使用Freebase API。以下是我使用的示例查询:http://tinyurl.com/3ogpf7k
这是我正在使用的JavaScript代码:
// App.q contains city name field's value
var query = {
extended : 1,
query : [{
search : App.q,
type : '/location/citytown',
id : null,
name : null,
postal_codes : [],
"/location/location/containedby" : [{
"type" : "/location/us_state",
"name": null,
// two letters abbreviation of state
"/common/topic/alias" : []
}]
}]
},
url = 'http://www.freebase.com/api/service/mqlread?callback=?&query=' +
encodeURIComponent(JSON.stringify(query));
$.getJSON(url, function( data ) {
var cities, i, len, name, aliases, j, abbr, postal_code, HTML = [];
for ( i = 0, len = data.result.length; i < len; i += 1 ) {
// cities with names matching user's input
if ( data.result[ i ].name.toLowerCase().indexOf( App.q ) === -1 ) continue;
// cities that have postal_codes data available
if ( data.result[ i ].postal_codes.length === 0 ) continue;
name = data.result[ i ].name;
aliases = data.result[ i ]["/location/location/containedby"][0]["/common/topic/alias"];
postal_code = data.result[ i ].postal_codes[0];
// find two-letters alias
for ( j = aliases.length - 1; j >= 0; j -= 1 ) {
if ( aliases[j].length === 2 && aliases[j] === aliases[j].toUpperCase() ) {
abbr = aliases[j];
}
}
HTML.push( D.renderHTML( liTemplate, {
name : name,
abbr : abbr,
postal_code : postal_code
}) );
}
console.log( HTML.join('') );
});
然而,查询“纽约”似乎并未返回“纽约市”。
是否有更好的API满足我的需求?我是否在使用Freebase API做错了什么?
UPD。另一个有用的API允许做同样的事情(它仍然不会削减我的需求 - 结果太多而无法通过它们进行分页):
文件:http://www.geonames.org/export/web-services.html
示例:http://api.geonames.org/postalCodeSearch?placename=los%20angeles&username=demo&maxRows=500
谢谢!
答案 0 :(得分:1)
对以前的误导性答案感到抱歉。我没有注意到你使用的是MQL扩展名“search”而不是“name”属性。
主要问题是默认排序不是通过搜索得分(不确定原因,但这就是它的方式)。修改this之类的查询应该可以解决问题:
"search": {"query":"New York","score":null,"type_strict":"all"},
"sort":"-search.score",
"type":"/location/citytown",
sort参数按“搜索”子查询返回的“得分”值按降序排序。您还可以使用mql_filter参数进行搜索,使其甚至不考虑不符合约束条件的事情(效率稍高)。