import com.alibaba.fastjson.JSON;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Delete;
import io.searchbox.core.Index;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.aihelp.development.platform.util.UUIDUtils;
import java.io.IOException;
import java.io.Serializable;
@Slf4j
public class Test {
private static JestClient jestClient=null;
private static String TABLE_NAME="test_user";
private static String TYPE="_doc";
static {
JestClientFactory factory=new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig.Builder("http://127.0.0.1:9200")
.multiThreaded(true)
.build());
jestClient=factory.getObject();
}
/**
* insert && update
*/
public static void insert(){
User user=new User(UUIDUtils.getUUID(),"北京",11);
Index index = new Index.Builder(user).index(TABLE_NAME).type(TYPE).id(UUIDUtils.getUUID()).refresh(true).build();
try {
JestResult result = jestClient.execute(index);
if(!result.isSucceeded()){
String errorMessage = result.getErrorMessage();
log.error("TranHistory save errorMessage:" + errorMessage);
}
} catch (Exception e) {
log.error("TranHistory save error" + e);
}
}
/**
* batch insert && batch update
* @throws IOException
*/
public static void batchUpdate() throws IOException {
Bulk.Builder bulk = new Bulk.Builder().defaultIndex(TABLE_NAME).defaultType(TYPE).refresh(true);
String id1="9be9c6d6672f4f888675da56e072c5e4";
User user1=new User(id1,"小放",15);
Index index1 = new Index.Builder(JSON.toJSON(user1)).index(TABLE_NAME).type(TYPE).id(user1.getId()).refresh(true).build();
bulk.addAction(index1);
String id2="8b7ab9c4274841ee8d369f2b8914da6c";
User user2=new User(id2,"小放",15);
Index index2 = new Index.Builder(user1).index(TABLE_NAME).type(TYPE).id(user2.getId()).refresh(true).build();
bulk.addAction(index2);
BulkResult br = jestClient.execute(bulk.build());
boolean succeeded = br.isSucceeded();
}
/**
* delete
* @throws IOException
*/
public static void del() throws IOException {
Bulk.Builder bulk = new Bulk.Builder().defaultIndex(TABLE_NAME).defaultType(TYPE).refresh(true);
Delete dr = new Delete.Builder("9be9c6d6672f4f888675da56e072c5e4").index(TABLE_NAME).type(TYPE).id("9be9c6d6672f4f888675da56e072c5e4").refresh(true).build();
bulk.addAction(dr);
BulkResult br = jestClient.execute(bulk.build());
boolean succeeded = br.isSucceeded();
}
@AllArgsConstructor
@Data
public static class User implements Serializable{
private String id;
private String name;
private Integer age;
}
}
12-24
2617
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交