// 倒排索引
# 重置 elastic 用户密码
docker exec -it es bin/elasticsearch-reset-password -u elastic
# 生成 Kibana 注册令牌(登录控制台用)
docker exec -it es bin/elasticsearch-create-enrollment-token -s kibana
# 端口记牢: 9200 是 ES 服务端口(程序连的), 9300 是集群内部通信端口
IK中文分词器
分词器选项 特点 适用
standard 默认,按空格 / 标点 简单英文
ik_smart 粗粒度,最少切分 适合检索
ik_max_word 细粒度,穷举可能词 适合关键词提取
docker exec es bin/elasticsearch-plugin install <IK 插件安装链接>
docker restart es
docker exec es bin/elasticsearch-plugin list # 查看已装插件
// 创建索引库
PUT /index_name
{
"mappings": {
"properties": {
"id": { "type": "long" },
"create_date": { "type": "date" },
"target_obj": {
"type": "object",
"index": true,
"properties": {
"sub_attr": { "type": "text", "index": true, "analyzer": "ik_smart" },
"other_sub_attr": { "type": "text", "index": false, "analyzer": "ik_smart" }
}
}
}
}
}
// 查 / 改 / 删
GET /index_name # 查索引库
PUT /index_name/_mapping # 增量更新 mapping(只能加字段/改 index,不能改已存在的字段类型)
DELETE /index_name # 删索引库
// 文档CRUD
// 增(指定 id)
POST /index_name/_doc/doc_id
{
"key": "value",
"key2": { "sub_key": "sub_value" }
}
// 删
DELETE /index_name/_doc/doc_id
// 改(全量:先删再增,id 不存在则新增)
PUT /index_name/_doc/doc_id
{
"key": "new_value"
}
// 改(局部:只改指定字段)
POST /index_name/_update/doc_id
{
"doc": {
"key": "new_value"
}
}
// 查
GET /index_name/_doc/doc_id
// 分词匹配
GET /index_name/_search
{
"query": {
"match": { "key": "value" } // 分词后匹配(text 字段用这个)
}
}
// 精确匹配
GET /index_name/_search
{
"query": {
"term": { "id": 1 } // 精确匹配,不分词(keyword/数值用这个)
}
}
// 布尔查询
{
"query": {
"bool": {
"must": [ { "match": { "title": "搜索词" } } ], // 必须满足(算分)
"should": [ { "match": { "title": "搜索词" } } ], // 最好满足(加分)
"must_not": [ { "match": { "title": "搜索词" } } ], // 必须不满足
"filter": [ { "range": { "create_date": { "gte": "start", "lte": "end" } } } ] // 过滤(不算分,快)
}
}
}
// 高亮范围查询
{
"query": {
"range": {
"create_time": { "gte": "2020-01-01", "lte": "2020-01-31" }
}
},
"highlight": {
"fields": {
"key": {
"pre_tags": ["<span style='color:red;'>"],
"post_tags": ["</span>"]
}
}
}
}
// SpringDataElasticsearch
// application.yml
spring:
elasticsearch:
uris: https://localhost:9200
username: elastic
password: <password>
connection-timeout: 5s
socket-timeout: 25s
ssl:
verification-mode: none
// 实体类
@Document(indexName = "index_name", createIndex = false)
public class Article {
@Id
private Long id;
@Field(type = FieldType.Date, format = DateFormat.date_time)
private Instant create_date;
@Field(type = FieldType.Object)
private TargetObj target_obj;
public static class TargetObj {
@Field(type = FieldType.Text, analyzer = "ik_smart")
private String sub_attr;
@Field(type = FieldType.Text, analyzer = "ik_smart", index = false)
private String other_sub_attr;
// getter & setter 省略
}
// getter & setter 省略
}
@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
// 方法名自动解析:按 target_obj.sub_attr 分页查
Page<Article> findByTargetObjSubAttr(String keyword, Pageable pageable);
// 复杂查询用 @Query 注解,?0 ?1 ?2 代表第 1/2/3 个参数
@Query("""
{ "bool": { "must": [ {"match": {"target_obj.sub_attr": "?0"}} ],
"filter": [ {"range": {"create_date": {"gte": "?1", "lte": "?2"}}} ] } }
""")
Page<Article> searchByKeywordAndDate(String keyword, String start_date, String end_date, Pageable pageable);
}
@Service
@RequiredArgsConstructor
public class ArticleService {
private final ArticleRepository articleRepository;
private final ElasticsearchOperations elasticsearchOperations;
private final ElasticsearchClient esClient;
// 新增:传新对象 save;修改:查出来改再 save
public Article save(Article article) {
return articleRepository.save(article);
}
public Article getById(Long id) {
return articleRepository.findById(id).orElse(null);
}
public void delete(Long id) {
articleRepository.deleteById(id);
}
// 高亮 + 布尔 + 分页搜索
public Page<Article> searchHighlight(String keyword, String startDate, String endDate, int page, int size) {
NativeQuery nativeQuery = NativeQuery.builder()
.withQuery(q -> q.bool(
b -> b.must(m -> m.match(ma -> ma.field("target_obj.sub_attr").query(keyword)))
.filter(f -> f.range(r -> r.field("create_date")
.gte(JsonData.of(startDate)).lte(JsonData.of(endDate))))
))
.withPageable(PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "create_date")))
.withHighlight(Highlight.builder().fields("target_obj.sub_attr",
HighlightField.builder().options(HighlightOptions.builder()
.preTags("<span style='color:red;'>").postTags("</span>").build()).build()).build())
.build();
SearchHits<Article> hits = elasticsearchOperations.search(nativeQuery, Article.class);
List<Article> list = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
return new PageImpl<>(list, PageRequest.of(page, size), hits.getTotalHits());
}
// 局部更新
public void updatePart(Long id, Article updateDoc) throws IOException {
UpdateRequest<Article, Article> req = UpdateRequest.of(
u -> u.index("index_name").id(id.toString()).doc(updateDoc)
);
esClient.update(req, Article.class);
}
// 高性能批量写入
public void bulkSave(List<Article> articleList) throws IOException {
if (CollectionUtils.isEmpty(articleList)) return;
List<BulkOperation> ops = new ArrayList<>();
for (Article article : articleList) {
ops.add(BulkOperation.of(o -> o.index(
i -> i.index("index_name").id(article.getId().toString()).document(article)
)));
}
BulkResponse resp = esClient.bulk(BulkRequest.of(b -> b.operations(ops)));
if (resp.errors()) {
throw new RuntimeException("Bulk写入失败: " + resp.items());
}
}
// 精确匹配(term,不分词)
public List<Article> termQuery(Long idVal) {
Criteria criteria = new Criteria("id").is(idVal);
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
return elasticsearchOperations.search(criteriaQuery, Article.class)
.stream().map(SearchHit::getContent).collect(Collectors.toList());
}
// 多字段同时检索
public Page<Article> multiMatchSearch(String kw, int page, int size) {
NativeQuery q = NativeQuery.builder()
.withQuery(qb -> qb.multiMatch(m -> m
.fields("target_obj.sub_attr", "target_obj.other_sub_attr")
.query(kw).analyzer("ik_smart")))
.withPageable(PageRequest.of(page, size))
.build();
SearchHits<Article> hits = elasticsearchOperations.search(q, Article.class);
List<Article> data = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
return new PageImpl<>(data, PageRequest.of(page, size), hits.getTotalHits());
}
}