阿里云服务器--Elasticsearch配置

一、申请注册

Elasticsearch 是一个基于 Lucene 的搜索服务,它提供了 RESTful web 接口的分布式、多用户全文搜索引擎 。Elasticsearch 是用 Java 开发的,并作为 Apache 许可条款下的开放源码发布,是第二大最流行的企业搜索引擎。
Elasticsearch 应用于云计算中,具有实时搜索、稳定、可靠、快速、安装使用方便等优势;但也存在一些安全隐患:默认安装完成后,Elasticsearch 可以使用 9200 端口通告 web 的方式访问查看数据信息。
文档地址:https://help.aliyun.com/document_detail/57876.html?spm=a2c4g.11186623.6.550.25468d0faHVf4B
注意:
创建ES时,VPC的选择一定要注意,如果连ECS,一定要和ECS在同一个VPC。

二、ES访问测试

(一)密码重置

密码重置

(二)登录控制台Kibana

Kibana是一个开源的分析和可视化平台,设计用于和Elasticsearch一起工作。
你用Kibana来搜索,查看,并和存储在Elasticsearch索引中的数据进行交互。
你可以轻松地执行高级数据分析,并且以各种图标、表格和地图的形式可视化数据。
Kibana使得理解大量数据变得很容易。它简单的、基于浏览器的界面使你能够快速创建和共享动态仪表板,实时显示Elasticsearch查询的变化。


登录控制台Kibana

Kibana控制台

(三)ECS VPC配置

如果ECS要访问EC需配置VPC:
经典网络问题:
如果是经典网络需做如下设置

1、为专有网络创建Classiclink

专有网络创建Classiclink
打开Classiclink
打开ClassicLink

在ECS控制台,选择开启了 classicLink 的 VPC 所在 Region

2、连接到专有网络

连接到专有网络

连接状态

登陆链接了 Classiclink 的ECS实例,通过 curl 的形式访问对应 VPC 网络环境中的阿里云Elasticsearch实例验证。


创建实例

[root@iz2ze78abfa21jjsp4u9wmz ~]# curl -XPOST -u elastic:hrz123456! 'http://es-cn-mp911l8uh001qzcfj.elasticsearch.aliyuncs.com:9200/filebeat/my_type/'?pretty -d '{"title": "One", "tags": ["ruby"]}'
执行命令:
PUT filebeat

ES访问测试

设置公网地址访问白名单:


公网地址访问白名单

三、创建文档

开启自动创建索引。


开启自动创建索引
修改配置
允许自动创建索引

curl http://:9200/my_index/my_type -XPOST -d '{"title": "One", "tags": ["ruby"]}'
my_index :是索引名称。
:表示阿里云ES实例内网/公网地址。
每个文档都拥有自己的 ID 和 type,在返回的结果中会显示响应的 ID 和 type,如果在创建时没有指定,则系统会为其随机生成一个。
注意:
如果您已开启自动创建索引(默认关闭),并且指定的 index 名称不存在,则在创建 document 时,系统将自动创建 index

四、更新文档

若Elasticsearch中存在文档,可使用如下语句更新文档。
http://:9200/my_index/my_type/
:表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。
:表示文档标识ID。
curl http://:9200/my_index/my_type/AV4JIvi15ny3i8DCdK1H -XPOST -d '{"title": "Four updated", "tags": ["ruby", "php"]}'

五、检索文档

可以通过HTTP GET对文档进行检索查询:
$ curl http://:9200/my_index/my_type/AV4JIvi15ny3i8DCdK1H
:表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。

六、搜索文档

可以通过HTTP GET或HTTP POST对文档进行搜索,通过 URI 参数制定搜索对象,目标如下:
http://:9200/_search
http://:9200/{index_name}/_search
http://:9200/{index_name}/{type_name}/_search
:表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。
例如:
$ curl http://:9200/my_index/my_type/_search?q=title:T*
:表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。

七、复杂搜索

必须使用HTTP POST对文档进行复杂搜索:
$ curl http://:9200/my_index/my_type/_search?pretty=true -XPOST -d '{
"query": {
"query_string": {"query": "*"}
},
"facets": {
"tags": {
"terms": {"field": "tags"}
}
}}'

:表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。
温馨提示:
使用?pretty=true是为了让返回结果更具可读性。

八、 删除文档

$ curl http://:9200/{index}/{type}/{id} -XDELETE
  • 表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。

九、删除指定类型对文档

$ curl http://:9200/{index}/{type} -XDELETE
  • 表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。

十、删除一个索引

$ curl http://:9200/{index} -XDELETE
  • 表示阿里云ES实例内网/公网地址,详情请参见阿里云ES实例基本信息界面。

十一、Java语言

需要先创建对应索引和mapping或者[开启自动创建索引]
注意:
ES官方已不建议通过TransportClient来访问Elasticsearch,使用TransportClient 5.5.3版在建立连接时会报 NoNodeAvailableException 问题,并且ES官方已经不再维护TransportClient。如果已经使用并且有提示报错,可用以下方法绕过:

  • 建议换成[Java Low Level REST Client]来访问Elasticsearch。
  • 在Java maven项目的[POM配置文件]中,使用 x-pack-transport-5.3.3 版client进行访问,并且POM配置文件中的elasticsearch版本也必须为5.3.3版,不建议通过该方案来绕着实现,不保证能完全兼容。

(一)Maven配置

要先创建对应索引和mapping或者开启自动创建索引。
分词配置

YML文件配置

代码:

接口:
public interface IESRestService {
    /**
     * 同步方式向ES集群写入数据
     *
     * @param index
     * @param type
     * @param id
     * @param entity
     * @return
     */
    boolean syncCreateDocument(String index, String type, String id, HttpEntity entity);

    /**
     * 异步的方式向ES写入数据
     *
     * @param index
     * @param type
     * @param id
     * @param entity
     */
    void asyncCreateDocument(String index, String type, String id, HttpEntity entity);

    /**
     * 创建索引
     * @param index
     */
     void createIndex(String index);
    /**
     * 获取文档
     * @param index
     * @param type
     * @param id
     * @return
     */
     String getDocument(String index, String type, String id);

    /**
     * 查询所有数据
     * @param index
     * @param type
     * @return
     */
     String queryAll(String index, String type);

    /**
     * 根据ID获取
     * @param index
     * @param type
     * @param key
     * @param value
     */
     void queryById(String index, String type, String key, String value);

    /**
     * 更新数据
     * @param index
     * @param type
     * @param id
     * @param key
     * @param value
     */
    void updateByScript(String index, String type, String id, String key, String value);
}
Java实现类:
@Service
public class ESRestServiceImpl implements IESRestService {

    private static String userName = "elastic";
    private static String password = "hrz123456!";
    private static String host = "es-cn-mp911l8uh001qzcfj.public.elasticsearch.aliyuncs.com";
    private static int port = 9200;
    private RestClient restClient = null;

    public static RestClient getInstance() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
        RestClient restClient = RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
        return restClient;
    }

    @PostConstruct
    public void init() {
        restClient = ElasticsearchUtils.getInstance();
    }

    @PreDestroy
    public void destroy() {
        if (restClient != null) {
            try {
                restClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 同步方式向ES集群写入数据
     *
     * @param index
     * @param type
     * @param id
     * @param entity
     * @return
     */
    @Override
    public boolean syncCreateDocument(String index, String type, String id, HttpEntity entity) {
        Response indexResponse = null;
        try {
            indexResponse = restClient.performRequest(
                    "PUT",
                    "/" + index + "/" + type + "/" + id,
                    Collections.emptyMap(),
                    entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (indexResponse != null);
    }

    /**
     * 异步的方式向ES写入数据
     *
     * @param index
     * @param type
     * @param id
     * @param entity
     */
    public void asyncCreateDocument(String index, String type, String id, HttpEntity entity) {
        /**
         *  HTTP的方法,可以是PUT,POST,DELETE,HEAD,GET等
         *  endpoint, 这个就是指数据在ES中的位置,由index,type以及id确定
         *  是一个map指的是操作数,即目标数据,这个例子里面表示要存入ES的数据对象
         *  异步操作的监听器,在这里,注册listener,对操作成功或者失败进行后续的处理,比如在这里向前端反馈执行后的结果状态
         */
        restClient.performRequestAsync(
                "PUT",
                "/" + index + "/" + type + "/" + id,
                Collections.emptyMap(),
                entity,
                new ResponseListener() {
                    @Override
                    public void onSuccess(Response response) {
                        System.out.println(response);
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        System.out.println("异步操作失败!");
                    }
                });
    }

    /**
     * 创建索引
     *
     * @param index
     */
    @Override
    public void createIndex(String index) {
        String method = "PUT";
        String endpoint = "/" + index;
        Response response = null;
        try {
            response = restClient.performRequest(method, endpoint);
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文档
     *
     * @param index
     * @param type
     * @param id
     * @return
     */
    public String getDocument(String index, String type, String id) {
        String method = "GET";
        String result = null;
        String endpoint = "/" + index + "/" + type + "/" + id;
        Response response = null;
        try {
            response = restClient.performRequest(method, endpoint);
            result = EntityUtils.toString(response.getEntity());
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询所有数据
     *
     * @param index
     * @param type
     * @return
     */
    public String queryAll(String index, String type) {
        String result = null;
        try {
            String method = "POST";
            String endpoint = "/" + index + "/" + type + "/_search";
            HttpEntity entity = new NStringEntity("{\n" +
                    "  \"query\": {\n" +
                    "    \"match_all\": {}\n" +
                    "  }\n" +
                    "}", ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
            result = EntityUtils.toString(response.getEntity());
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据ID获取
     *
     * @param index
     * @param type
     * @param key
     * @param value
     */
    public void queryById(String index, String type, String key, String value) {
        String method = "POST";
        String endpoint = "/" + index + "/" + type + "/_search";
        HttpEntity entity = new NStringEntity("{\n" +
                "  \"query\": {\n" +
                "    \"match\": {\n" +
                "      \"" + key + "\": \"" + value + "\"\n" +
                "    }\n" +
                "  }\n" +
                "}", ContentType.APPLICATION_JSON);
        Response response = null;
        try {
            response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新数据
     *
     * @param index
     * @param type
     * @param id
     * @param key
     * @param value
     */
    public void updateByScript(String index, String type, String id, String key, String value) {
        try {
            String method = "POST";
            String endpoint = "/" + index + "/" + type + "/" + id + "/_update";
            HttpEntity entity = new NStringEntity("{\n" +
                    "  \"doc\": {\n" +
                    "    \"" + key + "\":\"" + value + "\"\n" +
                    "   }\n" +
                    "}", ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试结果:

你可能感兴趣的:(阿里云服务器--Elasticsearch配置)