solr经纬度查询操作

package com.example.utils;

import com.google.gson.GsonBuilder;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;
import java.util.Iterator;

public class SolrClass {
    public static void main(String[] args) throws SolrServerException, IOException {

        SolrClient solr =  new HttpSolrClient("http://127.0.0.1:8983/solr/community_address/");
//        addData(solr);
        queryDistance(solr,"113.231895","23.152971");

    }

    private static void queryDistance(SolrClient server,String lng ,String lat) throws SolrServerException, IOException {
        SolrQuery params = new SolrQuery();
        params.set("q", "*:*");
        params.set("fq", "{!geofilt}");//距离过滤函数
        params.set("pt", String.format("%s,%s",lat,lng)); //当前经纬度(纬度,经度)
        params.set("sfield", "location"); //要检索的字段 在 managed-schema.xml 中配置   即可
        params.set("d", "1"); //就近 d km的所有数据
        //params.set("score", "kilometers");
        params.set("sort", "geodist() asc");  //根据距离排序:由近到远
        params.set("start", "0");  //记录开始位置
        params.set("rows", "100");  //查询的行数
        params.set("fl", "*,_dist_:geodist(),score");//查询的结果中添加距离和score


        System.out.println(params.toQueryString());
        QueryResponse query = server.query(params);
        SolrDocumentList results = query.getResults();
        Iterator iterator = results.iterator();
        while (iterator.hasNext()) {
            SolrDocument next = iterator.next();
            String s = new GsonBuilder().create().toJson(next, SolrDocument.class);
            System.out.println(s);
        }
        
        //搜索结果为
//        {"name":"鹅掌坦地铁站","location":"23.156818,113.235802","id":"1086cedc-09aa-4276-bd07-f67f3be64e01","_version_":1769120584056176640,"_dist_":0.58519244,"score":1.0}

    }

    private static void addData(SolrClient solr) {
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("name", "鹅掌坦地铁站");
        doc.addField("location", "23.156818,113.235802");

        try {
            solr.add(doc);
            solr.commit();
        } catch (SolrServerException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

你可能感兴趣的:(solr,java,lucene)