1. 程式人生 > >java操作elasticsearch 5.6.0查詢、插入

java操作elasticsearch 5.6.0查詢、插入

需注意:

1、ES5*以上版本需要jdk1.8

2、1.8JDK需tomcat 8


一、新建maven專案,新增依賴

<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
		</dependency>
		<dependency>
			<groupId>jdk.tools</groupId>
			<artifactId>jdk.tools</artifactId>
			<version>1.8</version>
			<scope>system</scope>
			<systemPath>C:/Program Files/Java/jdk1.8.0_144/lib/tools.jar</systemPath>
		</dependency>

		<dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.0</version>
        </dependency>
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>transport</artifactId>
			<version>5.6.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.7</version>
		</dependency>
	</dependencies>
二、新建log4j相關檔案

在main資料夾下新建resource資料夾,新建log4j.properties和log4j2.xml

log4j.properties

    appender.console.type = Console
    appender.console.name = console
    appender.console.layout.type = PatternLayout

    rootLogger.level = info
    rootLogger.appenderRef.console.ref = console

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN">

    <Appenders>

       <Console name="Console" target="SYSTEM_OUT">

          <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

       </Console>

    </Appenders>

    <Loggers>

       <Root level="error">

          <AppenderRef ref="Console"/>

       </Root>

    </Loggers>

</Configuration>

三、查詢

在es中新建索引/blog/article ,插入幾條資料;
(注意:這裡IP地址寫自己在elasticsearch.yml中寫的network.host,port就寫9300,雖然自己設定的es叢集port是9200

    public static void main(String[] args) {
    try {
    	
        //設定叢集名稱

        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //建立client
        @SuppressWarnings("resource")
		TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("0.0.0.0"), 9300));
        //寫入資料
       // createDate(client);
        //搜尋資料
        GetResponse response = client.prepareGet("blog", "article", "1").execute().actionGet();
        //輸出結果
        System.out.println(response.getSource());
        
        //關閉client
        client.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

四、插入單條資料

(因為在查詢時已經建立client,因此這裡直接引入了,單獨插入需單獨建立)

 /**
    * 插入單條資料
    * @param client
    */
    public static void createDate(Client client){
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("title", "紅樓夢");
    	map.put("content", "重生之我是賈寶玉");
    	map.put("newcontent", new String[]{"first","我是賈寶玉"}) ;
    	map.put("about", "i'd like to play");
    	try {
    		IndexResponse response = client.prepareIndex("blog", "article",UUID.randomUUID().toString())
                    .setSource(map).execute().actionGet();
    		System.out.println("寫入資料結果=" + response.status().getStatus() + "!id=" + response.getId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}