solr 空间搜索
现在的移动开发中,越来越多的app都有周边搜索功能。本文介绍怎么用solr来实现周边搜索。
首先构建一个常见的业务场景:搜索10KM以内的店铺信息,并且可以根据距离远近来排序。
一、配置schema.xml
<?xml version="1.0" ?> <schema name="master" version="1.5"> <types> <fieldtype name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/> <fieldtype name="location" class="solr.LatLonType" subFieldSuffix="_coordinate"/> <fieldType name="long" class="solr.TrieLongField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/> <fieldType name="int" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0" /> <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/> </types> <fields> <field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" /> <field name="name" type="string" indexed="true" stored="true" multiValued="false" /> <field name="url" type="string" indexed="true" stored="true" multiValued="false" /> <field name="businesshours" type="string" indexed="true" stored="true" multiValued="false" /> <field name="provinceCode" type="string" indexed="true" stored="true" multiValued="false" /> <field name="cityCode" type="string" indexed="true" stored="true" multiValued="false" /> <field name="storeAddress" type="string" indexed="true" stored="true" multiValued="false" /> <field name="geography" type="location" indexed="true" stored="true" multiValued="false" /> <field name="storeIntrodced" type="string" indexed="true" stored="true" multiValued="false" /> <field name="businessLicense" type="string" indexed="true" stored="true" multiValued="false" /> <field name="telephone" type="string" indexed="true" stored="true" multiValued="false" /> <dynamicField name="*_coordinate" type="double" indexed="true" stored="true" /> <field name="_version_" type="long" indexed="true" stored="true"/> </fields> <uniqueKey>id</uniqueKey> <defaultSearchField>name</defaultSearchField> <solrQueryParser defaultOperator="OR"/> </schema>
二、添加地理位置数据
数据格式为:(纬度,经度)
<field name="geography">30.904995063319802,120.65201489254832</field>
index.setGeography("30.904995063319802,120.65201489254832");
三、查询
solrQuery.addField("dist:geodist(geography,30.904995,120.652015)"); solrQuery.set("fq", "{!geofilt}"); solrQuery.set("pt", "30.904995,120.652015");
solrQuery.set("sfield", "geography");
solrQuery.set("d", "10");
// 按距离排序
solrQuery.addSortField("geodist()", ORDER.desc);