java api操作elasticsearch

Posted Nice&&Day

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java api操作elasticsearch相关的知识,希望对你有一定的参考价值。


elasticsearch的maven依赖
<dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.1.1</version>
            <scope>test</scope>
</dependency>
package com.cheguo.merchant.app.toolkit;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
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/14
 * Time: 下午3:13
 * Description:
 */
public class TestElk {
    public static void main(String[] args) {
        try {
            Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.10.13.7"),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)
                //避免分词后台把带奥或迪的都查询出来
                .operator(MatchQueryBuilder.Operator.AND);
        SearchResponse response = client.prepareSearch("carsrc").setTypes("carsource")
                .setSize(3)//每页显示条数
                .setFrom(3*0)//从那条开始查询
                .setQuery(queryBuilder).execute().actionGet();
        SearchHits searchHits = response.getHits();
        if(searchHits.totalHits()>0){
            for(SearchHit searchHit : searchHits){
                System.out.println("total>>>>"+searchHit.getType()+"source>>>"+searchHit.getSourceAsString());
            }
        }else{
            System.out.println("total 0");
        }
    }
    public static void put(Client client){
        UpdateRequest uRequest = new UpdateRequest();
        try {
            //uRequest = client.prepareUpdate("carsrc","carsource","243").setDoc(model2XContent()).get();
            uRequest.index("carsrc");
            uRequest.type("carsource");
            uRequest.id("243");
            uRequest.doc(jsonBuilder().startObject()
                    .field("car_source_id","232")
                    .field("car_source_code","")
                    .field("sales_region","")
                    .field("car_code","")
                    .field("car_id", "78732")
                    .field("car_name", "温州市")
                    .field("cars","")
                    .field("msrp","")
                    .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());
            client.update(uRequest).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //.prepareIndex("carsrc","carsource","1").
        //setSource(model2json()).get();
//        if(uRequest.) {
//            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_id","78732")
                    .field("car_source_id","243")
                    .field("sales_region","温州市")
                    .endObject();
        } 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;
    }
}

 

以上是关于java api操作elasticsearch的主要内容,如果未能解决你的问题,请参考以下文章

ElasticSearch04_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es

商城项目19_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es

商城项目19_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es

java api操作elasticsearch

elasticsearch java操作 api

ElasticSearch Java API