Java中使用elasticsearch搜索引擎实现简单查询、修改等操作-已在项目中实际应用

时间:2023-11-12 00:05:08

以下的操作环境为:jdk:1.8;elasticsearch:5.2.0

maven架包下载坐标为:

<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.nlpcn</groupId>
<artifactId>elasticsearch-sql</artifactId>
<version>6.3.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.0</version>
</dependency>

Java创建ES连接工具类:

//创建连接工具类
public class ESClientConnectionUtil {
public static TransportClient client=null;
public final static String HOST = "192.168.200.211"; //服务器部署
public final static Integer PORT = 9301; //端口
public static TransportClient getESClientConnection(){
if (client == null) {
System.setProperty("es.set.netty.runtime.available.processors", "false");
try {
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();
//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
return client;
} }

用Java命令想elasticsearch中插入数据

public Map<String,Object> addTopic(KnowledgeTopicDTO knowledgeTopicDTO){
Map<String,Object> map = new HashMap<>();
//连接ES
TransportClient transportClient = ESClientConnectionUtil.getESClientConnection();
JSONObject json = JSONObject.fromObject(knowledgeTopicDTO);//后台传过来的对象数据转换成json格式
try{
//index 索引名称(相当于数据库) type :类型(相当于数据库中的表)
IndexResponse response = transportClient.prepareIndex("knowledge", "knowledge_theme").setSource(json, XContentType.JSON).get();
if(null !=response.getId()){
map.put("code",200);
return map;
}
}catch (Exception e){
e.printStackTrace();
map.put("code",500);
return map;
}
return null;
}

使用Java根据id查询数据

//连接ES
TransportClient transportClient = ESClientConnectionUtil.getESClientConnection();
//参数:索引名,类型(type) id
GetResponse response = client.prepareGet("knowledge", "knowledge_theme", "1")
.setOperationThreaded(false) // 线程安全
.get();
JSONObject obj = new JSONObject().fromObject(response.getSourceAsString());//将json字符串转换为json对象
InformationDTO information = (InformationDTO) JSONObject.toBean(obj, InformationDTO.class);//将json数据转换成InformationDTO实体对象
String codes =response.getId();//获取_id

根据id进行修改数据(传入对象)

//knowledgeTopic为修改数据的对象
//修改状态后的对象转换成json数据
JSONObject fromObject= JSONObject.fromObject(knowledgeTopic);
//参数:索引名,类型(type) id(指的是_id) 要修改的json数据:fromObject
UpdateResponse updateResponse = client.prepareUpdate("knowledge", "knowledge_theme", "1")
.setDoc(fromObject).get();

根据id修改数据(针对单个字段修改)

   XContentBuilder source = null;
try {
source = XContentFactory.jsonBuilder()
.startObject()
.field("browseNum", num) //browseNum:要修改的字段名,num 修改的值
.endObject();
} catch (IOException e) {
e.printStackTrace();
}
//client:ES连接 codes为文档的_id
UpdateResponse updateResponse = client.prepareUpdate("article", "up_information", codes).setDoc(source).get();

  

ES模糊查询

SearchResponse searchResponse=null;
//连接elasticsearch
TransportClient transportClient = ESClientConnectionUtil.getESClientConnection();
searchResponse = client.prepareSearch()
.setIndices("knowledge")
.setTypes("knowledge_theme")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setScroll(TimeValue.timeValueMinutes(30)) //游标维持时间
.setSize(2 * 5)//实际返回的数量为10*index的主分片数
.setQuery(QueryBuilders.wildcardQuery("name", ("*"+name+"*").toLowerCase())) //查询的字段名及值
.execute()
.actionGet();

以上功能本人已亲测过,都能实现,希望这对大家有所帮助!转发请说明出处,本人的博客地址为:https://www.cnblogs.com/chenyuanbo/

技术在于交流!