java调用elasticsearch api详解

elasticsearch提供了多种语言的api,这里选择java来调用elasticsearch api,通过创建索引,修改索引,删除索引,查询索引等实例来讲解如何调用。另外讲解四种方式构建elasticsearch创建索引时所需的json document对象。

一、创建maven项目,引入elasticsearch相关依赖。


        org.elasticsearch.client
        transport
        6.3.0


        org.apache.logging.log4j
        log4j-api
        2.10.0
 
 
        org.apache.logging.log4j
        log4j-core
        2.10.0
 
  
        com.carrotsearch
        hppc
        0.8.1
  
  
        com.fasterxml.jackson.core
        jackson-databind
        2.8.10
  

二、编写elasticsearch操作核心实例。

java调用elasticsearch api详解_第1张图片

三、编写增删改查索引接口

索引

java调用elasticsearch api详解_第2张图片

运行索引方法,打印信息如下:

java调用elasticsearch api详解_第3张图片

然后,查看索引数据:http://10.119.9.149:9200/books/book/_search

java调用elasticsearch api详解_第4张图片

搜索

java调用elasticsearch api详解_第5张图片

控制台结果:

java调用elasticsearch api详解_第6张图片

修改

java调用elasticsearch api详解_第7张图片

运行结果:

java调用elasticsearch api详解_第8张图片

删除


删除之后,再次查看索引,已经没有任何记录了。

java调用elasticsearch api详解_第9张图片

四、介绍四种方式构建json document对象。

1、直接通过字符串构建。

java调用elasticsearch api详解_第10张图片

2、通过Map来构建。

java调用elasticsearch api详解_第11张图片

3、通过jackson-databind库来构建。

java调用elasticsearch api详解_第12张图片

4、通过jsonBuilder()来构建。

java调用elasticsearch api详解_第13张图片

运行完四种json方式构建索引之后,再次查看记录。

{
	took: 2,
	timed_out: false,
	_shards: {
		total: 5,
		successful: 5,
		skipped: 0,
		failed: 0
	},
	hits: {
		total: 4,
		max_score: 1,
		hits: [{
			_index: "books",
			_type: "book",
			_id: "HZQWNWQBRcxIEy9KMksQ",
			_score: 1,
			_source: {
				name: "Think in java",
				desc: "Think in java",
				price: 59.9,
				publish: "2018-04-01"
			}
		},
		{
			_index: "books",
			_type: "book",
			_id: "H5QYNWQBRcxIEy9Kuku2",
			_score: 1,
			_source: {
				name: "java in action",
				desc: "a book about java program",
				price: 29.9,
				publish: "2018-01-02"
			}
		},
		{
			_index: "books",
			_type: "book",
			_id: "IJQZNWQBRcxIEy9KpEte",
			_score: 1,
			_source: {
				name: "redis in action",
				desc: "redis reference",
				price: 19.9,
				publish: "2018-02-01"
			}
		},
		{
			_index: "books",
			_type: "book",
			_id: "HpQXNWQBRcxIEy9KKEvI",
			_score: 1,
			_source: {
				price: 36.9,
				publish: "2018-05-30",
				name: "elasticsearch in action",
				desc: "a book about elasticsearch"
			}
		}]
	}
}

最后,附上所有代码:

package com.xxx.es;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;

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

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxx.es.entity.Book;

@SuppressWarnings("resource")
public class App {
	private static TransportClient client;
	static{
		try {
			
			Settings settings = Settings.builder().put("cluster.name","hadoop").build();
			client = new PreBuiltTransportClient(settings)
			         .addTransportAddress(new TransportAddress(InetAddress.getByName("10.119.9.149"),9300));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void index(){
		Map source = new HashMap();
		source.put("name", "elasticsearch in action");
		source.put("desc", "a book about elasticsearch");
		source.put("price", 36.9);
		source.put("publish", "2018-05-30");
		IndexResponse response = client.prepareIndex("books", "book")
				                 .setSource(source).execute().actionGet();
		System.out.println("status:"+response.status().getStatus()+" , response id : "+response.getId());
	}
	
	public static void search(){
		SearchResponse result = client.prepareSearch("books")
		      .setTypes("book")
		      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
		      .setQuery(QueryBuilders.matchQuery("name", "action"))
		      .get();
		SearchHits hits  = result.getHits();
		for(SearchHit hit:hits){
			System.out.println(hit.getSourceAsMap());
		}
	}
	
	public static void update(){
		UpdateRequest request = new UpdateRequest("books", "book", "HJQANWQBRcxIEy9KSUtp");
		
		try {
			request.doc(jsonBuilder().startObject().field("desc", "elasticsearch book").endObject());
			client.update(request).get();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	public static void delete(){
		DeleteResponse response = client.prepareDelete("books", "book", "HJQANWQBRcxIEy9KSUtp").get();
		System.out.println(response.status());
	}
	
	public static void jsonByObject(){
		String json = "{"+
	           "\"name\":\"Think in java\"," + 
			   "\"desc\":\"Think in java\","+
	           "\"price\":59.9,"+
			   "\"publish\":\"2018-04-01\""+ 
	    "}";
		System.out.println(json);
		IndexResponse response = client.prepareIndex("books", "book")
				                .setSource(json,XContentType.JSON) 
			                  	.execute().actionGet();
		System.out.println("status : "+response.status());
	}
	
	public static void jsonByMap(){
		Map source = new HashMap();
		source.put("name", "elasticsearch in action");
		source.put("desc", "a book about elasticsearch");
		source.put("price", 36.9);
		source.put("publish", "2018-05-30");
		IndexResponse response = client.prepareIndex("books", "book")
				                 .setSource(source)
				                 .execute().actionGet();
		System.out.println("status : "+response.status());
	}
	
	public static void jsonByJackson(){
		ObjectMapper mapper = new ObjectMapper();
		Book book = new Book();
		book.setName("java in action");
		book.setDesc("a book about java program");
		book.setPrice(29.9);
		book.setPublish("2018-01-02");
		try {
			byte[] json = mapper.writeValueAsBytes(book);
			IndexResponse response = client.prepareIndex("books","book")
					                 .setSource(json,XContentType.JSON)
					                 .execute().actionGet();
			System.out.println("status : "+response.status());
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}	
	}
	
	public static void jsonByJsonBuilder(){
		//
		try {
			IndexResponse response = client.prepareIndex("books", "book")
					                 .setSource(jsonBuilder()
					                		   .startObject()
					                		   .field("name", "redis in action")
					                		   .field("desc", "redis reference")
					                		   .field("price", 19.9)
					                		   .field("publish", "2018-02-01")
					                		   .endObject())
					                 .execute().actionGet();
			System.out.println("status : "+response.status());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
    public static void main( String[] args ){
    	//index();
    	//search();
    	//update();
    	//delete();
    	//jsonByObject();
    	//jsonByMap();
    	//jsonByJackson();
    	jsonByJsonBuilder();
    }
}

例子中用到的Book实例:

package com.xxx.es.entity;

public class Book {
	private String name;
	private String desc;
	private double price;
	private String publish;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getPublish() {
		return publish;
	}
	public void setPublish(String publish) {
		this.publish = publish;
	}
	@Override
	public String toString() {
		return "Book [name=" + name + ", desc=" + desc + ", price=" + price
				+ ", publish=" + publish + "]";
	}
	
}

java调用elasticsearch api就介绍到这里。

你可能感兴趣的:(elasticsearch,java,api,java)