java api操作elasticsearch实现搜索查询


 
 
elasticsearch的maven依赖
<dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.1.1</version>
            <scope>test</scope>
</dependency>
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yangxianyu
 * Date: 2017/12/25
 * Time: 下午3:00
 * Description:
 */
public class TestElk {
    public static void main(String[] args) {
//        ApplicationContext context = new ClassPathXmlApplicationContext("file:F:\\ly\\cheguoservice\\user\\src\\main\\resources\\conf\\applicationContext.xml");
//        ICheChongQueryService cheChongQueryServiceImpl = (ICheChongQueryService) context.getBean("cheChongQueryServiceImpl");
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("vin", "LGBH12E08GY461536");//LGBH12E08GY461536
//        params.put("city", "杭州");
//        for (int i = 0; i < 10; i++) {
//            LoanApplyVinInfoVo ll = cheChongQueryServiceImpl.queryCarDetialByVin(params);
//            System.out.println(JSON.toJSON(ll));
//        }
//        String json = "{\"carname\":\"maobao\",\"price\":\"23\"}";
//        Carsrc carsrc = JSONObject.parseObject(json,Carsrc.class);
//        System.out.println(carsrc.toString());
//        System.out.println(JSON.toJSON(carsrc));
        try {
            Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.10.13.7"),9300))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.10.13.11"),9300));
            get(client);
            //put(client);
            //setMapping(client);
            client.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
    public static void get(Client client){
        String query = "温州市";
        String[] str = new String[3];
        str[0] = "car_name";
        str[1] = "cars";
        if(isNumeric(query)){
            str[2] = "sale_price";
        }
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(query,str)
//防止数字类型字段查询报错 .lenient(true)
//避免分词后台把带奥或迪的都查询出来 .operator(MatchQueryBuilder.Operator.AND); SearchResponse response = client.prepareSearch("carsrc").setTypes("carsource") .setSize(100)//每页显示条数 .setFrom(100*0)//从那条开始查询 .setQuery(queryBuilder).execute().actionGet(); SearchHits searchHits = response.getHits(); if(searchHits.totalHits()>0){ for(SearchHit searchHit : searchHits){ System.out.println("total>>>>"+searchHits.totalHits()+"|source>>>"+searchHit.getSourceAsString()); } }else{ System.out.println("total 0"); } } public static void put(Client client){ IndexResponse indexResponse = client.prepareIndex("carsrc","carsource","321456"). setSource(model2json()).get(); if(indexResponse.isCreated()) { System.out.println("add success"); } } public static void setMapping(Client client) { try { PutMappingResponse response = client.admin().indices() .preparePutMapping("carsrc") .setType("carsource") .setSource(XContentFactory.jsonBuilder() .startObject() .startObject("car_name") .startObject("cars") .field("analyzer", "whitespace") .field("type", "string") .endObject() .endObject() .endObject()) .execute().actionGet(); } catch (IOException e) { e.printStackTrace(); } } public static String model2json(){ String jsondata = ""; try { XContentBuilder xContentBuilder = jsonBuilder(); xContentBuilder.startObject() .field("car_source_id","321456") .field("car_source_code","") .field("sales_region","") .field("car_code","") .field("car_id", "78732") .field("car_name", "温州市") .field("cars","") .field("msrp","11") .field("sale_price","") .field("over_msrp","") .field("car_color","") .field("car_trim_color","") .field("remark","") .field("source_type","") .field("source_kind","") .field("source_status","") .field("product_date","") .field("procedure","") .field("car_vin","") .field("area_code","") .field("area_name","") .field("status","") .field("company_id","") .field("company_name","") .field("order_user_id","") .field("pay_user_id","") .field("transport","") .field("plate_limit","") .field("validate","") .field("valid_status","") .field("buy_deposit","") .field("sale_deposit","") .field("pay_order_id","") .field("score","") .field("company_type","") .field("come_from","") .field("brand_logo","") .field("pic_flag","") .field("cost_price","") .field("mini_price","") .field("reason","") .field("real_price","") .field("number","") .field("bill","") .field("source_flag","2") .field("gmt_create",new Date()) .field("gmt_modify",new Date()) .field("price_type","") .field("price_value","") .endObject(); jsondata = xContentBuilder.string(); } catch (IOException e) { e.printStackTrace(); } return jsondata; } public static XContentBuilder model2XContent(){ XContentBuilder xContentBuilder = null; try { xContentBuilder = jsonBuilder(); xContentBuilder.startObject().field("","") .field("","") .endObject(); } catch (IOException e) { e.printStackTrace(); } return xContentBuilder; } public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM