基于ElasticSearch7.5.1基本操作(HTTP方式)

China☆狼群 提交于 2020-08-05 02:02:46
依赖
<dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
</dependency>

    /**
     * 创建索引
     * @throws IOException
     */
    private static void createIdx() throws IOException {
        String mapping = 
			{
	"mappings": {
		"properties": {
			"user": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_max_word"
			},
			"title": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_max_word"
			},
			"desc": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_max_word"
			}
		}
	}
}

        System.out.println(service.doPut("http://localhost:9200/users", mapping, headers,null));
    }

    /**
     * 创建或者更新用户信息
     * @throws IOException
     */
    private static void createOrUpdateUser() throws IOException {
        User user = new User(1L,"Lisa","HR", "人力资源管理");
        System.out.println(user);
        System.out.println(service.doPost("http://localhost:9200/users/_doc/" + user.getId(), new Gson().toJson(user), headers,null));
    }

    /**
     * 删除用户信息
     * @throws IOException
     */
    private static void deleteUser() throws IOException {
        System.out.println(service.doDelete("http://localhost:9200/users/_doc/1"));
    }

    /**
     * 根据用户ID获取用户信息
     * @throws IOException
     */
    private static void getUserById() throws IOException {
        System.out.println(service.doGet("http://localhost:9200/users/_doc/1", null,null));
    }

    /**
     * 获取所有的用户信息
     * @throws IOException
     */
    private static void getAllUser() throws IOException {
        System.out.println(service.doGet("http://localhost:9200/users/_search", null,null));
    }

    /**
     * 条件获取用户信息
     * @throws IOException
     */
    private static void  getConditionUser() throws IOException {
        String params = "{\"query\" : { \"match\" : { \"desc\" : \"搬砖\" }}, \"from\": 0, \"size\":100}";
        System.out.println(service.doPost("http://localhost:9200/users/_search", params, headers,null));
    }

HTTP请求具体封装省略,自行封装

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!