1、pom引入maven依赖
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.70</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、application.yml文件增加配置
spring:
  data:
    elasticsearch:
      cluster-name:  elasticsearch
      cluster-nodes: 192.168.1.33:9300
      repositories:
        enabled: true
      properties:
        transport:
          tcp:  
            connect_timeout: 120s
3、定义model,映射到索引库

索引库名称:blog_1
document: blog
多个field中定义了mapping的类型,以及是否不在resource里存储,单独存储。分词方式等。

@Data
@Document(indexName = "blog_1", shards = 5, replicas = 1)
public class Blog {//type类型为blog
	
	@Field(type = FieldType.Long, store = true)
	private Long id;

	// type = FieldType.Text 字段类型为text
	// analyzer = "ik_max_word" 分词器为"ik_max_word"
	// store = true 存储 => 是
	@Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
	private String title;

	@Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
	private String content;

	@Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
	private String comment;

	@Field(type = FieldType.Keyword, store = true)
	private String mobile;

}
4、service

接口继承了ElasticsearchRepository,里面写的接口方法并没有实现,ElasticsearchRepository会分析方法名称。

public interface BlogRepository extends ElasticsearchRepository<Blog, Long> {
    /**
     * 定义一个方法查询:根据title查询es
     *
     * 原因:  ElasticsearchRepository会分析方法名,参数对应es中的field
     * @param title
     * @return java.util.List<com.yt.cubemall.search.model.Blog>
     */
    List<Blog> findByTitle(String title);

	/**
     * 定义一个方法查询: 根据title,content查询es
     */
    List<Blog> findByTitleAndContent(String title, String content);
}
5、请求接口
@RestController
@RequestMapping("/blogController")
public class BlogController {
	
	@Autowired
    private BlogRepository blogRepository;

    /**
     * 添加文档
     */
    @RequestMapping("/addDocument")
    public ResponseEntity<?> addDocument(){
        
        for (int i = 0; i < 100; i++) {
        	Blog blog = new Blog();
            blog.setId((long)i+1);
            blog.setTitle("越野路书"+i+1);
            blog.setContent("《越野路书》是汽车测评节目《萝卜报告》在2016年出品的一档自驾探险纪录片的视频节目"+i+1);
            blog.setComment("注释内容"+i+1);
            blog.setMobile("12345678");
            blogRepository.save(blog);
        }
        return writeToClient("成功",null);
    }
    
    /**
     * 更新文档
     */
    @RequestMapping("/updateDocument")
    public void updateDocument(){
        Optional<Blog> optional = blogRepository.findById(1l);
        if (optional.isPresent()){
            Blog blog = optional.get();
            blog.setTitle("hello update");
            blogRepository.save(blog);
        }
    }

    /**
     * 删除文档
     */
    @RequestMapping("/deleteDocument")
    public void deleteDocument() {
        blogRepository.deleteById(1l);
    }


    /**
     * 查询所有 文档
     */
    @RequestMapping("/getDocumentList")
    public ResponseEntity<?> getDocument() {
        //根据id查找
        //Optional<Blog> optional = blogRepository.findById(1l);
        //Blog blog = optional.get();
        //System.out.println(blog);

        //查找全部
        //Iterable<Blog> all = blogRepository.findAll();
        //all.forEach(blog -> System.out.println(blog));

        //分页查找全部
        Iterable<Blog> all = blogRepository.findAll(PageRequest.of(1,1000));
        System.out.println(all);
        all.forEach(blog -> System.out.println(blog));
        
        return writeToClient("成功",JSONObject.toJSONString(all));
    }
    
    /**
     * 自定义方法:根据title内容查询索引库
     *
     */
    @RequestMapping("testFindByTitle")
    public ResponseEntity<?> testFindByTitle(){
        List<Blog> blogList = blogRepository.findByTitle("41");
        blogList.stream().forEach(System.out::println);
        
        return writeToClient("成功",JSONObject.toJSONString(blogList));
    }

	/**
     * 自定义方法:根据title,content内容查询索引库
     */
    @RequestMapping("testFindByTitleAndContent")
    public ResponseEntity<?> testFindByTitleAndContent(){
        List<Blog> blogList = blogRepository.findByTitleAndContent("越野", "萝卜");
        blogList.stream().forEach(System.out::println);
        return writeToClient("成功",JSONObject.toJSONString(blogList));
    }
    
    public ResponseEntity<?> writeToClient(String msg,String obj){
		Map<String,Object> map = new HashMap<String,Object>();
    	map.put("res", 0);
		map.put("msg", msg);
		map.put("data",obj);
		return ResponseEntity.ok(map);
	}
}

参考文献
https://blog.csdn.net/qq_42347616/article/details/119754883

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐