赞
踩
新建springboot项目就不再赘述,相关教程非常多,很容查到。Elasticsearch在windows与linux环境下的安装与使用可以参考以下文章:
Linux/windows环境下后端基础服务(tomcat,MongoDB, docker, elasticsearch等)部署说明
es版本以自己安装的版本为准
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.41</version>
- </dependency>
-
- <dependency>
- <groupId>org.elasticsearch.client</groupId>
- <artifactId>elasticsearch-rest-high-level-client</artifactId>
- <version>7.13.2</version>
- </dependency>
可同时配置多个es连接
- server.port=9650
-
- spring.servlet.multipart.enabled=false
- spring.servlet.multipart.file-size-threshold=0
- spring.servlet.multipart.max-file-size=1MB
- spring.servlet.multipart.max-request-size=10MB
-
- elasticsearch.http.host=localhost
- elasticsearch.http.port=9200
- elasticsearch.user.index=user
- elasticsearch.user.type=userInfo
- package com.example.elasticsearchdemo.config;
-
- import org.apache.http.HttpHost;
- import org.elasticsearch.client.RestClient;
- import org.elasticsearch.client.RestClientBuilder;
- import org.elasticsearch.client.RestHighLevelClient;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class ElasticsearchConfig {
-
- @Value("${elasticsearch.http.host}")
- private String esHost;
- @Value("${elasticsearch.http.port}")
- private int esPort;
-
- @Bean
- public RestHighLevelClient esRestClient() {
- RestClientBuilder builder = null;
- builder = RestClient.builder(new HttpHost(esHost,esPort,"http"));
- RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
- return restHighLevelClient;
- }
-
- }
具体方法可参考文章:
映射如下:
- {
- "mappings": {
- "userInfo": {
- "properties": {
- "id": {
- "type": "text",
- "fields": {
- "keyword": {
- "type":"keyword",
- "ignore_above":256
- }
- }
- },
- "name": {
- "type": "text",
- "fields": {
- "keyword": {
- "type":"keyword",
- "ignore_above":256
- }
- }
- },
- "age": {
- "type": "integer",
- "fields": {
- "keyword": {
- "type":"keyword",
- "ignore_above":256
- }
- }
- },
- "sex": {
- "type": "text",
- "fields": {
- "keyword": {
- "type":"keyword",
- "ignore_above":256
- }
- }
- },
- "interest ": {
- "type": "text",
- "fielddata": true,
- "fields": {
- "keyword": {
- "type":"keyword",
- "ignore_above":256
- }
- }
- }
- }
- }
- }
- }
参考es映射新建对应的user类
- ackage com.example.elasticsearchdemo.bean;
-
- import org.springframework.data.annotation.Id;
-
- public class User {
-
- @Id
- private String id;
-
- private String name;
-
- private Integer age;
-
- private String sex;
-
- private String interest;
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- public String getSex() {
- return sex;
- }
-
- public void setSex(String sex) {
- this.sex = sex;
- }
-
- public String getInterest() {
- return interest;
- }
-
- public void setInterest(String interest) {
- this.interest = interest;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "id='" + id + '\'' +
- ", name='" + name + '\'' +
- ", age=" + age +
- ", sex='" + sex + '\'' +
- ", interest='" + interest + '\'' +
- '}';
- }
- }
注:若传入参数user对象包含id且es中已存在相同id,则更新替换;否则新建用户。条件查询中若传入map为空,则返回所有;否则执行多条件查询操作。
- package com.example.elasticsearchdemo.controller;
-
- import com.alibaba.fastjson.JSONObject;
- import com.example.elasticsearchdemo.bean.User;
- import com.example.elasticsearchdemo.service.UserService;
- import org.springframework.web.bind.annotation.*;
-
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- @RestController
- @RequestMapping("/user")
- @CrossOrigin(value = "*", maxAge = 3600)
-
- public class UserController {
-
- @Resource
- private UserService service;
-
- /**新增与修改用户*/
- @RequestMapping(value = "save", method = RequestMethod.POST)
- public JSONObject saveUser(@RequestBody User user) {
- JSONObject output = new JSONObject();
- Map<String, Object> result = service.saveUser(user);
- output.put("msg", result);
- return output;
- }
-
- /**删除用户*/
- @RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
- public JSONObject deleteUser(@PathVariable("id") String id) {
- JSONObject output = new JSONObject();
- Map<String, Object> result = service.deleteUser(id);
- output.put("msg", result);
- return output;
- }
-
-
- /**条件查询*/
- @RequestMapping(value = "get", method = RequestMethod.POST)
- public JSONObject getUsers(@RequestBody Map<String,Object> maps) throws Exception{
- JSONObject output = new JSONObject();
- List result = new ArrayList();
- if (maps != null) {
- result = service.getUsers(maps);
- } else {
- result = service.getAllUsers();
- }
- output.put("data", result);
- return output;
- }
-
- }
- package com.example.elasticsearchdemo.service;
-
- import com.example.elasticsearchdemo.bean.User;
- import com.example.elasticsearchdemo.dao.common.UserEsDao;
- import org.springframework.stereotype.Service;
-
- import javax.annotation.Resource;
- import java.util.List;
- import java.util.Map;
- import java.util.UUID;
-
- @Service
- public class UserService {
-
- @Resource
- private UserEsDao userEsDao;
-
- /**如果存在用户就修改,不存在就新增*/
- public Map<String, Object> saveUser(User user) {
- if (user.getId() == null) {
- //生成唯一随机id
- String id = UUID.randomUUID().toString().substring(24);
- user.setId(id);
- }
- return userEsDao.saveUser(user);
- }
-
- public Map<String,Object> deleteUser(String id) {
- return userEsDao.deleteUser(id);
- }
-
- public List getAllUsers() throws Exception{
- return userEsDao.getUsers(null);
- }
-
- public List getUsers(Map<String,Object> maps) throws Exception{
- return userEsDao.getUsers(maps);
- }
-
- }
- package com.example.elasticsearchdemo.dao.common;
-
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.example.elasticsearchdemo.bean.User;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.elasticsearch.action.bulk.BulkRequest;
- import org.elasticsearch.action.bulk.BulkResponse;
- import org.elasticsearch.action.delete.DeleteRequest;
- import org.elasticsearch.action.index.IndexRequest;
- import org.elasticsearch.action.search.SearchRequest;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.client.RequestOptions;
- import org.elasticsearch.client.RestHighLevelClient;
- import org.elasticsearch.index.query.*;
- import org.elasticsearch.search.SearchHit;
- import org.elasticsearch.search.builder.SearchSourceBuilder;
- import org.elasticsearch.search.sort.SortOrder;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Repository;
-
- import java.io.IOException;
- import java.util.*;
-
- @Repository
- public class UserEsDao {
-
- @Autowired
- private RestHighLevelClient client;
- @Value("${elasticsearch.user.index}")
- private String userIndex;
- @Value("${elasticsearch.user.type}")
- private String userType;
-
-
- /**
- * 往es中插入新数据
- */
- public Map<String, Object> saveUser(User user){
- Map<String,Object> ret = new HashMap<>();
-
- Map map = null;
- try{
- //实体转换成map以请求es
- map = JSON.parseObject(JSON.toJSONString(user), Map.class);
- }catch (Exception e){
- e.printStackTrace();
- }
-
- BulkRequest bulkRequest = new BulkRequest();
- //IndexRequest构造函数第三个参数指定id
- bulkRequest.add(new IndexRequest(userIndex,userType,user.getId()).source(map));
- try{
- BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
- ret.put("msg",bulkResponse);
- return ret;
- }catch (IOException e){
- ret.put("msg",e.getStackTrace());
- e.printStackTrace();
- }
- return ret;
- }
-
- /**
- * 从es中删除一条数据
- */
- public Map<String,Object> deleteUser(String id){
- Map<String,Object> ret = new HashMap<>();
- BulkRequest request = new BulkRequest();
- request.add(new DeleteRequest(userIndex,userType,id));
- try {
- BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
- ret.put("msg",bulkResponse);
- return ret;
- }catch (IOException e){
- ret.put("msg",e.getStackTrace());
- e.printStackTrace();
- }
- return ret;
-
- }
-
- /**
- * 条件查询
- */
- public List getUsers(Map<String,Object> maps) throws IOException {
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
- //判断是否是条件查询
- if (maps != null) {
- Set<String> keys = maps.keySet();
- for (String key: keys) {
- boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(key, maps.get(key)));
- }
- } else {
- MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
- boolQueryBuilder.should(matchAllQueryBuilder);
- }
- searchSourceBuilder.query(boolQueryBuilder).size(10).from(0).sort("age", SortOrder.DESC);//分页以及排序
- SearchRequest searchRequest = new SearchRequest();
- searchRequest.indices(userIndex);
- searchRequest.types(userType);
- searchRequest.source(searchSourceBuilder);
- SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
- List list = new ArrayList();
- for (SearchHit hit: searchResponse.getHits()) {
- String s = JSON.toJSONString(hit);
- JSONObject o = JSON.parseObject(s);
- list.add(o.getJSONObject("sourceAsMap"));
- }
- return list;
- }
-
- }
后续会更新springboot+elasticsearch空间检索示例。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。