Elasticsearch 介绍 Elasticsearch 7:快速上手 Elasticsearch 7:关于 Index、Type、Document Elasticsearch 7:安装与启动 Elasticsearch 7:Kibana 的使用 Elasticsearch 7:下载历史版本 Elasticsearch 7:文档唯一性 Elasticsearch 7:默认端口与端口设置 Elasticsearch 7:创建和删除索引 Elasticsearch 7:自定义 mapping 和 settings Elasticsearch 7:设置索引副本数量和分片数量 Elasticsearch 7:查看所有索引 Elasticsearch 7:数据类型 Elasticsearch 7:字符串类型 keyword 、text Elasticsearch 7:数组 Elasticsearch 7:添加和更新文档 Elasticsearch 7:通过 _bulk 批量添加文档 Elasticsearch 7:使用 from 、size 进行分页查询 Elasticsearch 7:查询中使用 sort 进行排序 Elasticsearch 7:查询结果只展示部分字段 Elasticsearch 7:查询结果中展示 _version 字段 Elasticsearch 7:使用 ignore_above 限制字符串长度 Elasticsearch 7:动态映射 Elasticsearch 7:doc_values 属性 Elasticsearch 7:刷新周期 refresh_interval Elasticsearch 7:使用 _refresh 刷新索引 Elasticsearch 7:分片(shard)限制 Elasticsearch 7:使用 _cat thread_pool 查询线程池运行情况 Elasticsearch 7:事务日志 translog Elasticsearch 7:文档 _id 的长度限制 Elasticsearch 7:分片 shard Elasticsearch 7:滚动查询 Elasticsearch 7:聚合查询 Elasticsearch 7:索引模板 Elasticsearch 7:获取文档所属的 shard Elasticsearch 7:获取版本号 Elasticsearch 7:获取指定 shard 中的文档 Elasticsearch 7:获取 shard 统计信息 Elasticsearch 7:搜索实战 Elasticsearch 7:Python 客户端 Elasticsearch 7:Java TransportClient API 客户端 Elasticsearch 7:Java REST Client API 客户端 Elasticsearch:将 SQL 转换为 DSL Elasticsearch 6 快速上手 Elasticsearch 5 快速上手 Elasticsearch 5:禁止自动创建索引 Elasticsearch 5:禁止动态增加字段 Elasticsearch 产品版本支持周期 基于 Elasticsearch 的站内搜索引擎实战

Elasticsearch 7:Java TransportClient API 客户端


#Elasticsearch


介绍

在 Elasticsearch 7 中已经说明该客户端将在 8.0 版本被废弃。

具体使用可参考 https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-api.html

该客户端是通过 9300 端口并使用 Elasticsearch 的原生传输协议和集群交互。集群中的节点通过端口 9300 彼此通信。

实战1

ES 版本 7.13.4

gradle 依赖:

compile 'org.elasticsearch.client:transport:7.13.4'
compile 'org.apache.logging.log4j:log4j-core:2.11.1'

数据准备

# 创建索引
PUT student
{
  "mappings" : {
    "properties" : {
      "uid": {
        "type" : "integer"
      },
      "name" : {
        "type" : "keyword"
      },
      "age" : {
        "type" : "integer"
      }
    }
  },
  "settings" : {
    "index" : {
      "number_of_shards" : 10,
      "number_of_replicas" : 1
    }
  }
}

# 插入数据
POST student/_doc/1?routing=1
{
  "uid": 1,
  "name": "张三",
  "age": 10
}

# 插入数据
POST student/_doc/2?routing=2
{
  "uid": 2,
  "name": "张三",
  "age": 10
}

查询数据:

# 请求
GET student/_search
{
  "query": {
    "match_all": {}
  },
  "explain": true
}

# 结果
{
  "took" : 25,
  "timed_out" : false,
  "_shards" : {
    "total" : 10,
    "successful" : 10,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_shard" : "[student][7]",
        "_node" : "gejvpvFJTTK8LAnyvaI3_Q",
        "_index" : "student",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_routing" : "2",
        "_source" : {
          "uid" : 2,
          "name" : "张三",
          "age" : 10
        },
        "_explanation" : {
          "value" : 1.0,
          "description" : "*:*",
          "details" : [ ]
        }
      },
      {
        "_shard" : "[student][8]",
        "_node" : "gejvpvFJTTK8LAnyvaI3_Q",
        "_index" : "student",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_routing" : "1",
        "_source" : {
          "uid" : 1,
          "name" : "张三",
          "age" : 10
        },
        "_explanation" : {
          "value" : 1.0,
          "description" : "*:*",
          "details" : [ ]
        }
      }
    ]
  }
}

查询 _id 为 1 的数据

package esdemo;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {


    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        GetResponse response = client.prepareGet("student", "_doc", "1").get();
        System.out.println(response);

        client.close();
    }
}

执行结果:

{"_index":"student","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"_routing":"1","found":true,"_source":{
  "uid": 1,
  "name": "张三",
  "age": 10
}
}

查询 _id 1 数据的详细信息

package esdemo;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        GetResponse response = client.prepareGet("student", "_doc", "1").get();
        System.out.println("返回结果:");
        System.out.println(response);
        System.out.println("索引名:");
        System.out.println(response.getIndex());
        System.out.println("文档id:");
        System.out.println(response.getId());
        System.out.println("文档内容:");
        System.out.println(response.getSource());
        System.out.println("name:");
        System.out.println(response.getSource().get("name"));

        client.close();
    }
}

执行结果:

返回结果:
{"_index":"student","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"_routing":"1","found":true,"_source":{
  "uid": 1,
  "name": "张三",
  "age": 10
}
}
索引名:
student
文档id:
1
文档内容:
{uid=1, name=张三, age=10}
name:
张三

基于 term 查询,结果有数据

package esdemo;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequest request = new SearchRequest();
        request.allowPartialSearchResults(false);
        request.indices("student");
        request.types("_doc");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "张三")));
        request.source(searchSourceBuilder);

        System.out.println("查询语句: ");
        System.out.println(searchSourceBuilder);

        ActionFuture<SearchResponse> searchResponseActionFuture =  client.search(request);
        SearchResponse searchResponse = searchResponseActionFuture.actionGet(1000);  // 参数 1000 是超时时间,毫秒
        System.out.println("查询结果:");
        System.out.println(searchResponse);
        client.close();
    }
}

执行结果:

查询语句: {
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "name": {
                            "value": "张三",
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    }
}
查询结果:
{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.0,
                "_routing": "2",
                "_source": {
                    "uid": 2,
                    "name": "张三",
                    "age": 10
                }
            },
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.0,
                "_routing": "1",
                "_source": {
                    "uid": 1,
                    "name": "张三",
                    "age": 10
                }
            }
        ]
    }
}

基于 term 查询,结果无数据

如果要查李四,则查不到:

package esdemo;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequest request = new SearchRequest();
        request.allowPartialSearchResults(false);
        request.indices("student");
        request.types("_doc");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "李四")));
        request.source(searchSourceBuilder);

        System.out.println("查询语句: ");
        System.out.println(searchSourceBuilder);

        ActionFuture<SearchResponse> searchResponseActionFuture =  client.search(request);
        SearchResponse searchResponse = searchResponseActionFuture.actionGet(1000);
        System.out.println("查询结果:");
        System.out.println(searchResponse);
        client.close();
    }
}

执行结果:

查询语句: {
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "name": {
                            "value": "李四",
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    }
}
查询结果:
{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

基于 term 查询,指定 routing

package esdemo;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequest request = new SearchRequest();
        request.allowPartialSearchResults(false);
        request.indices("student");
        request.types("_doc");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "张三")));
        request.routing("1"); // 指定 routing
        request.source(searchSourceBuilder);

        System.out.println("查询语句: ");
        System.out.println(searchSourceBuilder);

        ActionFuture<SearchResponse> searchResponseActionFuture =  client.search(request);
        SearchResponse searchResponse = searchResponseActionFuture.actionGet(1000);
        System.out.println("查询结果:");
        System.out.println(searchResponse);
        client.close();
    }
}

执行结果:

查询语句: {
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "name": {
                            "value": "张三",
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    }
}
查询结果:
{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.0,
                "_routing": "1",
                "_source": {
                    "uid": 1,
                    "name": "张三",
                    "age": 10
                }
            }
        ]
    }
}

基于 term 查询,指定分片

package esdemo;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequest request = new SearchRequest();
        request.allowPartialSearchResults(false);
        request.indices("student");
        request.types("_doc");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "张三")));
        searchSourceBuilder.explain(true);
        request.preference("_shards:0");  // 指定分片
        request.source(searchSourceBuilder);

        System.out.println("查询语句: ");
        System.out.println(searchSourceBuilder);

        ActionFuture<SearchResponse> searchResponseActionFuture =  client.search(request);
        SearchResponse searchResponse = searchResponseActionFuture.actionGet(1000);
        System.out.println("查询结果:");
        System.out.println(searchResponse);
        client.close();
    }
}

执行结果:

查询语句: {
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "name": {
                            "value": "张三",
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "explain": true
}
查询结果:
{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

request.preference("_shards:0"); 换成 request.preference("_shards:7");,则执行结果为:

查询语句: {
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "name": {
                            "value": "张三",
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "explain": true
}
查询结果:
{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_shard": "[student][7]",
                "_node": "gejvpvFJTTK8LAnyvaI3_Q",
                "_index": "student",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.0,
                "_routing": "2",
                "_source": {
                    "uid": 2,
                    "name": "张三",
                    "age": 10
                },
                "_explanation": {
                    "value": 0.0,
                    "description": "ConstantScore(name:张三)^0.0",
                    "details": []
                }
            }
        ]
    }
}

基于 term 滚动查询 - 简单示例

package esdemo;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequestBuilder searchRequestBuilder = client.prepareSearch();
        searchRequestBuilder.setIndices("student");
        searchRequestBuilder.setTypes("_doc");
        searchRequestBuilder.setAllowPartialSearchResults(false);
        searchRequestBuilder.setTimeout(TimeValue.timeValueMillis(1000));
        searchRequestBuilder.setSize(1);

        searchRequestBuilder.setScroll(TimeValue.timeValueMinutes(1)); // 设置滚动查询

        searchRequestBuilder.setQuery(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "张三")));

        SearchResponse searchResponse = searchRequestBuilder.get();
        System.out.println("查询结果:");
        System.out.println(searchResponse);
        client.close();
    }
}

执行结果:

查询结果:
{
    "_scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlkDnF1ZXJ5VGhlbkZldGNoChZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_UWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_YWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_cWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_gWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_kWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_4WZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_oWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_sWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_wWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAJ_0WZ2VqdnB2RkpUVEs4TEFueXZhSTNfUQ==",
    "took": 38,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.0,
                "_routing": "2",
                "_source": {
                    "uid": 2,
                    "name": "张三",
                    "age": 10
                }
            }
        ]
    }
}

基于 term 滚动查询 - 滚动所有数据

package esdemo;

import org.elasticsearch.action.search.*;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestClient {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        SearchRequestBuilder searchRequestBuilder = client.prepareSearch();
        searchRequestBuilder.setIndices("student");
        searchRequestBuilder.setTypes("_doc");
        searchRequestBuilder.setAllowPartialSearchResults(false);
        searchRequestBuilder.setTimeout(TimeValue.timeValueMillis(1000));
        searchRequestBuilder.setSize(1);
//        searchRequestBuilder.setPreference("_shards:7");

        searchRequestBuilder.setScroll(TimeValue.timeValueMinutes(1)); // 设置滚动查询

        searchRequestBuilder.setQuery(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("name", "张三")));

        SearchResponse searchResponse = searchRequestBuilder.get();
        System.out.println("查询结果:");
        System.out.println(searchResponse);

        String scrollId = searchResponse.getScrollId();

        if (searchResponse.getHits().getHits().length == 0) {
            System.out.println("结束滚动查询");
            ClearScrollRequestBuilder clearScrollRequestBuilder = client.prepareClearScroll();
            clearScrollRequestBuilder.addScrollId(scrollId);
            ClearScrollResponse clearScrollResponse = clearScrollRequestBuilder.get();
            System.out.println("清理结果:");
            System.out.println(clearScrollResponse.isSucceeded());
            return;
        }

        // 继续查,直至滚动结束
        while (true) {
            SearchScrollRequestBuilder scrollRequestBuilder = client.prepareSearchScroll(searchResponse.getScrollId());
            scrollRequestBuilder.setScroll(TimeValue.timeValueMinutes(1));
            searchResponse = scrollRequestBuilder.get();
            System.out.println("查询结果:");
            System.out.println(searchResponse);
            scrollId = searchResponse.getScrollId();
            if (searchResponse.getHits().getHits().length == 0) {
                System.out.println("结束滚动查询");
                break;
            }
        }

        // 清理 scrollId
        if (scrollId != null) {
            ClearScrollRequestBuilder clearScrollRequestBuilder = client.prepareClearScroll();
            clearScrollRequestBuilder.addScrollId(scrollId);
            ClearScrollResponse clearScrollResponse = clearScrollRequestBuilder.get();
            System.out.println("清理结果:");
            System.out.println(clearScrollResponse.isSucceeded());
        }

        client.close();
    }
}

执行结果:

查询结果:
{
    "_scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlkDnF1ZXJ5VGhlbkZldGNoChZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSEWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKR8WZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSMWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSAWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSIWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSgWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSUWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKScWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSQWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSYWZ2VqdnB2RkpUVEs4TEFueXZhSTNfUQ==",
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.0,
                "_routing": "2",
                "_source": {
                    "uid": 2,
                    "name": "张三",
                    "age": 10
                }
            }
        ]
    }
}
查询结果:
{
    "_scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlkDnF1ZXJ5VGhlbkZldGNoChZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSEWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKR8WZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSMWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSAWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSIWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSgWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSUWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKScWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSQWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSYWZ2VqdnB2RkpUVEs4TEFueXZhSTNfUQ==",
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.0,
                "_routing": "1",
                "_source": {
                    "uid": 1,
                    "name": "张三",
                    "age": 10
                }
            }
        ]
    }
}
查询结果:
{
    "_scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlkDnF1ZXJ5VGhlbkZldGNoChZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSEWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKR8WZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSMWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSAWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSIWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSgWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSUWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKScWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSQWZ2VqdnB2RkpUVEs4TEFueXZhSTNfURZqVlFic24yWlItNkxBMXlGdVp5SDNBAAAAAAAAKSYWZ2VqdnB2RkpUVEs4TEFueXZhSTNfUQ==",
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.0,
        "hits": []
    }
}
结束滚动查询
清理结果:
true

插入一条数据

package esdemo;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;


public class TestClient {

    public static void main(String[] args) throws IOException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("uid", "3")
                .field("name", "王五")
                .field("age", 11)
                .endObject();
        IndexResponse response = client.prepareIndex("student", "_doc", "3")
                .setRouting("3")
                .setSource(xContentBuilder)
                .get();

        System.out.println(response);
        System.out.println(response.getResult());

        client.close();
    }
}

执行结果:

IndexResponse[index=student,type=_doc,id=3,version=1,result=created,seqNo=0,primaryTerm=2,shards={"total":2,"successful":1,"failed":0}]
CREATED

查询数据:

GET student/_search
{
  "query": {
    "match_all": {}
  }
}

# 结果
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 10,
    "successful" : 10,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "student",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_routing" : "3",
        "_source" : {
          "uid" : "3",
          "name" : "王五",
          "age" : 11
        }
      },
      {
        "_index" : "student",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_routing" : "2",
        "_source" : {
          "uid" : 2,
          "name" : "张三",
          "age" : 10
        }
      },
      {
        "_index" : "student",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_routing" : "1",
        "_source" : {
          "uid" : 1,
          "name" : "张三",
          "age" : 10
        }
      }
    ]
  }
}



( 本文完 )