elasticsearch

elasticsearch

docker-compose: docker安装elasticsearch及ik分词器
简单使用:

docker pull elasticsearch:7.16.1

docker run -d --name elasticsearch\
  -p 9200:9200 -p 9300:9300\
  -e ES_JAVA_OPTS="-Xms256m -Xmx512m"\
  -e "discovery.type=single-node" elasticsearch:7.16.1

# 若需要挂载目录 example -> pwd: /opt/docker/xxx/elasticsearch
# docker logs -f elasticsearch 若启动失败 在data目录下创建nodes目录尝试 或 赋予权限
docker run -d --name elasticsearch\
  -p 9200:9200 -p 9300:9300\
  -e ES_JAVA_OPTS="-Xms256m -Xmx512m"\
  -v /opt/docker/xxx/elasticsearch/data:/usr/share/elasticsearch/data\
  -v /opt/docker/xxx/elasticsearch/plugins:/usr/share/elasticsearch/plugins
  -e "discovery.type=single-node" elasticsearch:7.16.1

elasticsearch-head 0.1.5
排除 spring-boot-starter-data-elasticsearch 自动装配

@SpringBootApplication(exclude = {
	ElasticsearchDataAutoConfiguration.class, 
	ElasticsearchRepositoriesAutoConfiguration.class, 
	ElasticsearchRestClientAutoConfiguration.class
})

spring官网-Elasticsearch Repositories
spring官网-CrudRepository
elasticsearch整合使用1
深层次学习

简单使用:

spring:
  elasticsearch:
    uris: http://192.168.93.27:9200
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Document(indexName = "books")
@Data
@Accessors(chain = true)
public class Book {
    @Id
    private Long id;

    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String name;

    @Field(type = FieldType.Text)
    private String summary;

    @Field(type = FieldType.Integer)
    private Integer price;
}
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.sundraw.cloud.demo.business.module.demo.entity.Book;
import com.sundraw.cloud.demo.business.module.demo.mapper.es.BookRepository;
import com.sundraw.cloud.web.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created on 2022/11/8.
 *
 * @author jh.wang
 */
@RestController
@RequestMapping("es")
public class EsController {
	@Autowired
	private BookRepository bookRepository;

	@GetMapping("query")
	public Result<List<Book>> query(String name, Integer price) {
		List<Book> byNameAndPrice = bookRepository.findByNameOrPrice(name, price);
		return Result.ok(byNameAndPrice);
	}

	@GetMapping("query/high")
	public Result<List<Book>> function(String name, String summary) {
		List<SearchHit<Book>> byNameOrSummary = bookRepository.findByNameOrSummary(name, summary);

		return Result.ok(byNameOrSummary.stream().map(hit -> {
			Book book = hit.getContent();
			Set<Map.Entry<String, List<String>>> entries = hit.getHighlightFields().entrySet();
			for (Map.Entry<String, List<String>> entry : entries) {
				String key = entry.getKey();
				if (CollUtil.isNotEmpty(entry.getValue())) {
					ReflectUtil.invoke(book, String.format("set%s", StrUtil.upperFirst(key)), entry.getValue().get(0));
				}
			}
			return book;
		}).collect(Collectors.toList()));
	}

	@PostMapping("add10")
	public Result<Void> function() {
		List<Book> books = new ArrayList<>();
		String randStr = "了解清楚随机一段废话到底是一种怎么样的存在, 是解决一切问题的关键.生活中, 若随机一段废话出现了, 我们就不得不考虑它出现了的事实. 总结的来说, 所谓随机一段废话, 关键是随机一段";
		Snowflake snowflake = IdUtil.getSnowflake(1);
		for (int i = 0; i < 10; i++) {
			int i1 = RandomUtil.randomInt(0, 20);
			int i2 = RandomUtil.randomInt(i1, randStr.length() - i1);
			String substring = randStr.substring(i1, i2);
			books.add(new Book().setId(snowflake.nextId())
					.setName(substring)
					.setSummary(RandomUtil.randomString(8))
					.setPrice(RandomUtil.randomInt(20, 50)));
		}

		bookRepository.saveAll(books);
		return Result.ok();
	}

	@GetMapping("query/page1")
	public Result<Page<Book>> page(Integer size, Integer page) {
		PageRequest request = PageRequest.of(page - 1, size, Sort.by("price").descending());
		Page<Book> pageData = bookRepository.findAll(request);
		return Result.ok(pageData);
	}

	@GetMapping("query/page2")
	public Result<Page<Book>> page2(Integer size, Integer page, String name) {
		PageRequest request = PageRequest.of(page - 1, size, Sort.by("price").descending());
		Page<Book> pageData = bookRepository.findByName(name, request);
		return Result.ok(pageData);
	}

	@GetMapping("query/high/page2")
	public Result<Page<Book>> page3(Integer size, Integer page, Integer price, String name) {
		PageRequest request = PageRequest.of(page - 1, size, Sort.by("price").descending());
		request.withSort(Sort.by("price").descending());
		SearchPage<Book> data = bookRepository.findByPriceBeforeOrName(price, name, request);

		List<Book> collect = data.get().map(hit -> {
			Book book = hit.getContent();
			Set<Map.Entry<String, List<String>>> entries = hit.getHighlightFields().entrySet();
			for (Map.Entry<String, List<String>> entry : entries) {
				if (CollUtil.isNotEmpty(entry.getValue())) {
					ReflectUtil.invoke(book, String.format("set%s", StrUtil.upperFirst(entry.getKey())), entry.getValue().get(0));
				}
			}
			return book;
		}).collect(Collectors.toList());

		PageImpl<Book> page1 = new PageImpl<>(collect, request, data.getTotalElements());
		return Result.ok(page1);
	}

	@DeleteMapping("/{id}")
	public Result<Void> delete(@PathVariable Long id) {
		bookRepository.deleteById(id);
		return Result.ok();
	}
}
import com.sundraw.cloud.demo.business.module.demo.entity.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.data.repository.Repository;

import java.util.List;

public interface BookRepository extends Repository<Book, Long> {
  List<Book> findByNameOrPrice(String name, Integer price);

  @Highlight(fields = {
          @HighlightField(name = "name"),
          @HighlightField(name = "summary")
  }, parameters = @HighlightParameters(
          preTags = "<span style='color: red;'>",
          postTags = "</span>"
  ))
  @SuppressWarnings("SpringDataRepositoryMethodReturnTypeInspection")
  List<SearchHit<Book>> findByNameOrSummary(String text, String summary);

  Iterable<Book> saveAll(Iterable<Book> book);

  Page<Book> findByName(String name, Pageable pageable);

  @Highlight(fields = {
          @HighlightField(name = "name"),
          @HighlightField(name = "summary")
  }, parameters = @HighlightParameters(
          preTags = "<span style='color: red;'>",
          postTags = "</span>"
  ))
  @SuppressWarnings("SpringDataRepositoryMethodReturnTypeInspection")
  SearchPage<Book> findByPriceBeforeOrName(Integer price,String name, Pageable pageable);

  void deleteById(Long id);

  Page<Book> findAll(Pageable pageable);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值