淘先锋技术网

首页 1 2 3 4 5 6 7

前期准备工作

安装Elasticsearch+Kibana

需要先安装好jdk(这个自行下载安装,就不过多说了)

官方下载地址点击下载https://www.elastic.co/cn/downloads/elasticsearch
建议不要下载过高版本的,也不要下载过低版本的,博主6、7、8版本都下载过,为别再出错,建议下载和我同一个版本,博主使用的是7.8.1。具体操作如下:

第一步:
在这里插入图片描述
第二步:
在这里插入图片描述

下载指定安装包后,选择合适的位置保存压缩包,并解压好,打开bin目录,在bin里打开cmd输入elasticsearch或者直接点击bin目录下面的slasticsearch.bat文件:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
成功启动后,由于内部的elasticsearch.yml配置并没有改动,因此可以直接浏览器访问http://localhost:9200/如果有一下信息则证明成功启动:
在这里插入图片描述
由于安装kibana步骤几乎和elasticsearch一样,所以就不多说了。
kibana下载地址点击下载https://www.elastic.co/cn/downloads/past-releases#kibana
经过同样的步骤操作后就可以浏览器访问点击访问http://localhost:5601/app/kibana#/dev_tools/console
在这里插入图片描述
在这里就可以向我们的es中进行数据操作(相当可视化界面)。
最终我们完成了全部的安装操作。

springboot整合Elasticsearch

配置本地连接es文件

#配置ElaticSearch
spring.elasticsearch.hostname=127.0.0.1
spring.elasticsearch.port=9200

连接配置es

@Configuration
public class EsConfig {
//配置本机地址以及端口
    @Value("${spring.elasticsearch.hostname}")
    private String hostname;
    @Value("${spring.elasticsearch.port}")
    private int port;
    /**
     * LowLevelRestConfig
     */
    @Bean
    public RestClient restClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
        RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port, "http"));
        // 设置Header编码
        Header[] defaultHeaders = {new BasicHeader("content-type", "application/json")};
        clientBuilder.setDefaultHeaders(defaultHeaders);
        return clientBuilder.build();
    }
    /**
     * HighLevelRestConfig
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
        return new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, "http")));
    }
}

下面就可以开始我们的crud操作了,由于单个模块发太过于繁琐,因此我就把我自己简化的每个层业务代码都发出来吧!

controller层

@Api(tags = {"es"})
@RestController
@RequestMapping("/es")
@Slf4j
public class EsController {


    @Autowired
    public RestHighLevelClient restHighLevelClient;
	@Autowired
	private IRestHighLevelClientService restHighLevelClientService;
	@Autowired
	private QueryDataService queryDataService;
	@Autowired
	private UserService userService;

	/**
	 * 创建索引
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/createIndex")
	@ApiOperation(value = "创建索引", notes = "创建索引")
	public String createIndex(@RequestBody Index index) throws IOException {
	     //String indexName = "user";
		restHighLevelClientService.createIndex(index.getIndexName());
		log.info("创建 {} 成功",index.getIndexName());
		return "create "+index.getIndexName()+" success";
	}

	/**
	 * 查询索引
	 * @return
	 * @throws IOException
	 */
    @GetMapping("/queryIndex")
    @ApiOperation(value = "查询索引", notes = "查询索引")
    public GetResponse contextLoads() throws IOException {
        GetRequest request = new GetRequest().index("mcy").id("1");
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
		log.info("查询索引数据:{}",response);
        return  response;
    }

	/**
	 * 查询数据
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/query")
	@ApiOperation(value = "查询数据", notes = "查询数据")
	public JSONArray getData() throws IOException {
		List<Mcy> result = new ArrayList<Mcy>();
		result = queryDataService.queryAll();
		JSONArray json = new JSONArray();
		for(Mcy m : result){
			JSONObject jo = new JSONObject();
			jo.put("id", m.getId());
			jo.put("name", m.getName());
            jo.put("creator",m.getCreator());
            jo.put("desc",m.getDesc());
            jo.put("price",m.getPrice());
            jo.put("tags",m.getTags());
			json.add(jo);
		}
		log.info("查询mcyFindAll数据为:{}",result);
		return json;
	}
	/**
	 * 删除索引
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/deleteIndex")
	@ApiOperation(value = "删除索引", notes = "删除索引")
	public String deleteIndex(@RequestBody String indexName) throws IOException {
        //String indexName="user";
		AcknowledgedResponse acknowledgedResponse = restHighLevelClientService.deleteIndex(indexName);
		log.info("删除 {} 成功",indexName);
		return "DeleteIndex "+indexName+" success";
	}

	/**
	 * 插入数据
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/saveDate")
	@ApiOperation(value = "插入数据", notes = "插入数据")
	public void saveDate(@RequestBody User user){
		log.info("user: {}",user);
		userService.save(user);
		log.info("插入 {} 成功",user.getName());
	}
	/**
	 * 通过name字段删除数据
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/deleteUser")
	@ApiOperation(value = "删除数据", notes = "删除数据")
	public String deleteUserByName(@RequestBody User user) throws IOException {
		User delUser = getUserByName(user);
        userService.deleteUserById(delUser);
		return "delete:"+user.getName()+"success!";
	}

	/**
	 * 从第一条数据开始查询,每页显示2条
	 * @return
	 * @throws IOException
	 */
	public void DocQueryfy() throws IOException {
		SearchRequest request = new SearchRequest("user");
		SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
		builder.from(0);
		builder.size(2);
		request.source(builder);
		SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
		SearchHits hits = response.getHits();
//		System.out.println(hits.getTotalHits());
//		System.out.println(response.getTook());
//		for (SearchHit hit : hits) {
//			System.out.println(hit.getSourceAsString());
//		}
		restHighLevelClient.close();
	}
    //私有方法,根据user的name字段值查询user所有数据(目前主要查询user的Id)
	private User getUserByName(User user)throws IOException{
		User resultUser = new User();
		SearchRequest request = new SearchRequest("user");
		//由于目前trem还不支持中文,因此需要在查询的字段字段值后加上.keyword,或者下载安装ik分词器插件
		request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name.keyword",user.getName())));
		SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
		SearchHits hit = response.getHits();
		log.info("hit:{}",hit);
		String id = hit.getHits()[0].getId();
		log.info("id:{}",id);
		resultUser.setId(id);
		resultUser.setName(user.getName());
		return resultUser;
	}

	/**
	 * 通过name字段修改数据
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/updateUser")
	@ApiOperation(value = "修改数据", notes = "修改数据")
	public String updateUserByName(@RequestBody User user) throws IOException {
		User updUser = getUserByName(user);
		updUser.setName(user.getNewName());
		userService.save(updUser);
		return "update:"+user.getName()+"success!";
	}

}

service层

public interface QueryDataService{

    List<Mcy> queryAll();

}

//以及其实现

@Repository
@Service
public class QueryDataServiceImp implements QueryDataService{

    @Autowired
    private QueryDataRepository queryDataRepository;

    @Override
    public List<Mcy> queryAll() {

        Iterable<Mcy> result = queryDataRepository.findAll();
        List<Mcy> list = Lists.newArrayList(result);
        return list;
    }
}


public interface UserService {

    void save(User user);

    void deleteUserById(User delUser);

}

//以及其实现

@Repository
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public void deleteUserById(User delUser) {
        userRepository.delete(delUser);
    }
}

repository层

@Repository
public interface QueryDataRepository extends ElasticsearchRepository<Mcy,String>{
}
//
public interface UserRepository extends ElasticsearchRepository<User,String> {
}

domain层

@Data
@Document(indexName = "user")
public class User implements Serializable {

    @Id
    private String Id;
    private String name;
    private String newName;

}
@Data
@Document(indexName = "mcy")
public class Mcy implements Serializable {
    @Id
    private String id;
    private String name;
    private String creator;
    private String desc;
    private long price;
    private List<String> tags;
}
@Data
public class Index implements Serializable {

    private String indexName;

}
以上便是整个增删改查操作的所有代码了,如果您看到了这里说明代码还是有点用处的,既然如此就顺手来一个点赞、
关注、收藏、评论呗!感谢支持!!!