package com.applesnt.onlinemall.search;
import com.alibaba.fastjson.JSON;
import com.applesnt.onlinemall.search.config.ElasticSearchConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OnlinemallSearchApplicationTests {
/*注入es操作对象*/
@Autowired
private RestHighLevelClient client;
/*构建一个实体类*/
@Data
@AllArgsConstructor
public class User{
private String name;
private Integer age;
private String gender;
}
@Test
public void saveIndex() throws IOException {
/*初始化一个用户对象*/
User user = new User("zhangsan",18,"男");
/*把user对象转换成json格式*/
String jsonUser = JSON.toJSONString(user);
/*索引操作对象,参数为索引名称*/
IndexRequest indexRequest = new IndexRequest("userindex");
/*设置文档id*/
indexRequest.id("1");
indexRequest.source(jsonUser, XContentType.JSON);
/*执行保存操作 ElasticSearchConfig为es配置类*/
IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
System.out.println(index);
}
}