java操作elasticsearch获取数据并创建索引以及查询

相关jar包的maven如下:

<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>transport</artifactId>
			<version>5.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.46</version>
		</dependency>

如果使用的是springboot,默认的elasticsearch的版本是2.4.6,亲测有bug,建议使用5.2.2.需要修改版本

    <properties>
		<elasticsearch.version>5.2.2</elasticsearch.version>
	</properties>

下面开始测试
首先写了个工具类来获取客户端对象

public Client getClient(){
		TransportClient client=null;
		try {
			Settings settings = Settings.builder()
			        .put("client.transport.sniff", true).build();
			client = new PreBuiltTransportClient(settings);
			//添加地址到client中
			client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return client;
	}

接下来查询员工数据并创建索引

@Test
	public void testCreateEmployeeIndexToES() throws Exception {
		Client client = getClient();
		List<Employee> list = employeeService.selectAll();
		for (Employee employee : list) {
			String empJson = JSON.toJSONString(employee);
			client.prepareIndex("test", "employee", employee.getId().toString())
					.setSource(empJson).get();
		}
	}

测试成功后进入kibana5服务管理平台
在这里插入图片描述
创建索引成功!
接下来测试模糊查询

@Test
	public void testWildcardQuery() throws Exception {
		Client client = getClient();
		WildcardQueryBuilder usernames = new WildcardQueryBuilder("username", "asd*");
		SearchResponse searchResponse = client.prepareSearch("test").setQuery(usernames).addSort("id", SortOrder.ASC).get();
		SearchHit[] hits = searchResponse.getHits().getHits();
		System.out.println("总条数:"+hits.length);
		for (SearchHit searchHit : hits) {
			Map<String, Object> source = searchHit.getSource();
			String empStr = JSON.toJSONString(source);
			Employee employee = JSON.parseObject(empStr, Employee.class);
			System.out.println(employee);
		}
	}

测试结果如下
在这里插入图片描述
要点总结:
创建索引需要把Employee对象转换成json字符串
而查询则需要将json字符串转换成Employee对象

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值