1、项目中需要依赖的ES包
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
首先,得创建一个REST客户端
// 创建Rest客户端
val client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.20.132", 9200 ,"http") ))
2、创建索引
def testIndex():Unit = {
val jsonMap = new JSONObject()
jsonMap.put("user", "AKUK")
jsonMap.put("postDate", new Date())
jsonMap.put("message", "trying out Elasticsearch")
val request = new IndexRequest("posts","doc","1").source(jsonMap)
val response = client.index(request)
print(response.getResult)
}
3、删除索引
def deleteIndex() : Unit = {
// 设置要删除的索引名称
val request = new DeleteIndexRequest("POSTS")
request.timeout(TimeValue.timeValueMinutes(2))
request.masterNodeTimeout(TimeValue.timeValueMinutes(1))
request.indicesOptions(IndicesOptions.lenientExpandOpen)
//同步执行
val deleteIndexResponse = client.indices.delete(request)
val acknowledged = deleteIndexResponse.isAcknowledged //是否所有节点都已确认请求
print("是否所有的节点已经确认:"+acknowledged);
//如果找不到索引,则会抛出ElasticsearchException:
try {
val request = new DeleteIndexRequest("does_not_exist")
client.indices.delete(request)
} catch {
case exception: ElasticsearchException =>
if (exception.status eq RestStatus.NOT_FOUND) {
//如果没有找到要删除的索引,要执行某些操作
}
}
}
4、修改数据
def testUpdateIndexField() : Unit = {
val request = new IndexRequest("posts","doc","1").source("user","AKUK")
val response = client.index(request)
print(response.getResult)
}
5、查询数据
/**
521
{"title":"In which order are my Elasticsearch queries executed?"}
{"title":"In which order are my Elasticsearch queries executed?"}
14
*/
def getRequest() : Unit = {
//
{
val l = System.currentTimeMillis()
val request = new GetRequest("posts", "doc", "1")
val response = client.get(request)
println(System.currentTimeMillis() - l)
//println(response.getSourceAsString)
//println(response.getSourceInternal)
}
// 同步按条件批量查询
{
val request = new GetRequest("posts", "doc", "1")
val includes = Array[String]("title")
val emptyarray = Strings.EMPTY_ARRAY
val context = new FetchSourceContext(true, includes, emptyarray)
request.fetchSourceContext(context)
val response1 = client.get(request)
println(response1.getSourceAsString)
}
// 异步实现查询
{
import java.util.concurrent.CountDownLatch
import org.elasticsearch.action.get.{GetRequest, GetResponse}
import org.elasticsearch.action.{ActionListener, LatchedActionListener}
val request = new GetRequest("posts", "doc", "1")
//tag::get-execute-listener
var listener = new ActionListener[GetResponse]() {
override def onResponse(getResponse: GetResponse): Unit = {
println(getResponse.getSourceAsString)
}
override def onFailure(e: Exception): Unit = {
// <2>
}
}
//end::get-execute-listener
// Replace the empty listener by a blocking listener in test
val latch = new CountDownLatch(1)
listener = new LatchedActionListener[GetResponse](listener, latch)
val l = System.currentTimeMillis()
//tag::get-execute-async
client.getAsync(request, listener)
//Thread.sleep(3000)
latch.await(30L, TimeUnit.SECONDS)
//end::get-execute-async
println(System.currentTimeMillis() - l)
}
}
6、批量操作
/**eg.1
* 1686
OK
OK
3003
eg.2
1147
OK
OK
29
*/
def testBulk() : Unit = {
val request = new BulkRequest()
val one = new IndexRequest("posts", "doc", "1").source(XContentType.JSON, "title", "In which order are my Elasticsearch queries executed?")
val two = new IndexRequest("posts", "doc", "2").source(XContentType.JSON, "title", "Current status and upcoming changes in Elasticsearch")
val three = new IndexRequest("posts", "doc", "3").source(XContentType.JSON, "title", "The Future of Federated Search in Elasticsearch")
request.add(one, two, three)
val l = System.currentTimeMillis()
// 同步操作
val response = client.bulk(request)
println(System.currentTimeMillis() - l)
println(response.status())
val s = System.currentTimeMillis()
var listener = new ActionListener[BulkResponse]() {
override def onResponse(getResponse: BulkResponse): Unit = {
println(getResponse.status())
}
override def onFailure(e: Exception): Unit = {
// <2>
}
}
//end::get-execute-listener
// Replace the empty listener by a blocking listener in test
val latch = new CountDownLatch(1)
listener = new LatchedActionListener[BulkResponse](listener, latch)
// 异步操作
client.bulkAsync(request, listener)
//Thread.sleep(3000)
latch.await(30L, TimeUnit.SECONDS)
println(System.currentTimeMillis() - s)
}