elasticsearch环境搭建和api编程

1.下载 Elasticsearch ,下载地址:https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.1.1.zip
解压文件,进入bin目录 单击“elasticsearch.bat”启动。

2.启动后,在浏览器输入如下命令
1:查看是否部署成功
  http://localhost:9200/

  如下说明成功:
  {
  "name" : "l5YPTqU",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "WMcmRohDSqSYPOtvF8Nb-A",
  "version" : {
    "number" : "5.1.1",
    "build_hash" : "5395e21",
    "build_date" : "2016-12-06T12:36:15.409Z",
    "build_snapshot" : false,
    "lucene_version" : "6.3.0"
  },
  "tagline" : "You Know, for Search"
}

2:查看健康情况
http://localhost:9200/_cat/health?v
如下:
epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1514450156 16:35:56  elasticsearch yellow          1         1    255 255    0    0      255             0                  -                 50.0%



下面是一些通过curl操作es的例子,_cat用于查看,_update用于更新,_bulk用于批量操作,_search用于查询。
具体的就不一一解释了。可参见官网:https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html

##To check the cluster health
curl 'localhost:9200/_cat/health?v'

##get a list of nodes in our cluster
curl 'localhost:9200/_cat/nodes?v'

##take a peek at our indices
curl 'localhost:9200/_cat/indices?v'

##create an index named "customer"
curl -XPUT 'localhost:9200/customer?pretty'

##index a simple customer document into the customer index,
"external" type, with an ID of 1
curl -XPUT 'localhost:9200/customer/external/1?pretty'-d
' { "name": "John Doe" }'



常用的插件head,bigdesk,essql 请先下载插件

安装命令如下:
bin/plugin --url file:///path/to/plugin --install plugin-name


3.搭建开发环境
<properties>
<log4j.version>2.7</log4j.version>
</properties>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.1.1</version>
</dependency>



<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<exclusions>
<exclusion>
<artifactId>elasticsearch</artifactId>
<groupId>org.elasticsearch</groupId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.1.1</version>
<exclusions>
<exclusion>
<artifactId>elasticsearch</artifactId>
<groupId>org.elasticsearch</groupId>
</exclusion>
</exclusions>
</dependency>


<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>




Java代码:

package com.example.demo;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkIndexByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.net.InetAddress;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@RunWith(SpringRunner.class)
//@SpringBootTest
public class DemoApplicationTests {

/**
* 获取客户端
* @return
* @throws Exception
*/
public TransportClient getClient() throws  Exception{
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "elasticsearch")
.put("client.transport.sniff", true).build();// 集群名
//创建client
TransportClient client  = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

return  client;
}

/**
* 创建索引
* @throws Exception
*/
@Test
public void addIndex() throws  Exception{
    TransportClient client = getClient();
    for(int i=22;i<24;i++) {
    String user ="user";//索引名称
    String message = "message";//类型
    String id =i+"";// id
IndexResponse response = client.prepareIndex(user, message, id)
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field("user", "kimchy"+i)
.field("postDate", new Date())
.field("message", "trying out Elasticsearch"+i)
.endObject()
)
.get();
System.out.println(response);
}


System.out.println("===");
client.close();
//输出结果
// IndexResponse[index=user22,type=message22,id=22,version=1,result=created,shards={"_shards":{"total":2,"successful":1,"failed":0}}]
// IndexResponse[index=user23,type=message23,id=23,version=1,result=created,shards={"_shards":{"total":2,"successful":1,"failed":0}}]
}


/**
* 获取索引
* @throws Exception
*/
@Test
public void getIndex() throws  Exception{
TransportClient client = getClient();
GetResponse response = client.prepareGet("user22","message22","22").get();
System.out.println(response.toString());
System.out.println("end:"+response.getSourceAsString());

client.close();
//输出结果
// {"_index":"user22","_type":"message22","_id":"22","_version":1,"found":true,"_source":{"user":"kimchy22","postDate":"2017-12-28T08:40:12.628Z","message":"trying out Elasticsearch22"}}
// end:{"user":"kimchy22","postDate":"2017-12-28T08:40:12.628Z","message":"trying out Elasticsearch22"}

}

/**
* 多条件获得多索引
* @throws Exception
*/
@Test
public void mutilGetIndex() throws Exception{
TransportClient client = getClient();

MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("user1", "message1", "1")
.add("user2", "message2", "2","3")
.add("user3", "message3", "3")
.get();

for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
GetResponse response = itemResponse.getResponse();
String result ="begin";
if (response.isExists()) {
String json = response.getSourceAsString();
result = result +json+";end";
}
System.out.println(result);
}
}

/**
* 按照id,类型,索引 删除索引
* @throws Exception
*/
@Test
public void deleteIndex() throws  Exception{
TransportClient client = getClient();
DeleteResponse response = client.prepareDelete("user3","message3","3").get();
System.out.println(response.toString());
System.out.println("end:"+response.status());

client.close();

}

/**
* 按照查询条件删除索引
* @throws Exception
*/
@Test
public void deletebyQueryIndex() throws  Exception{
TransportClient client = getClient();

BulkIndexByScrollResponse response =
DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("user", "kimchy")) //对应soure中的内容
.source("user")//索引名称
.get();

long deleted = response.getDeleted();

System.out.println("end::"+deleted);

client.close();

}


/**
* 按照条件查询获取索引
* @throws Exception
*/
@Test
public void searchIndex() throws  Exception{
TransportClient client = getClient();

SearchResponse response = client.prepareSearch("user1", "user2")
.setTypes("message1", "message2")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("user", "kimchy1"))                 // Query
//.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
.setFrom(0).setSize(60).setExplain(true)
.get();
System.out.println("response::"+response.toString());

SearchHit[] searchHit = response.getHits().getHits();
if(null !=searchHit && searchHit.length >0){
int len = searchHit.length;
for(int j=0;j<len;j++) {
SearchHit hit = searchHit[j];
System.out.println("id:"+hit.id()+";;type:"+hit.type()
+";source:"+hit.getSourceAsString());

}
}
System.out.println(response.getHits().getHits());
System.out.println("end==");



}



}



猜你喜欢

转载自gjp014.iteye.com/blog/2406061