spring data elasticsearch批量更新文档的某个字段

因为使用的是ElasticsearchTemplate模板的方法,故性能上可能会有点差,哪位大神有更好的见解,可以交流一下哈。

java方法如下:

@Autowired
    private ElasticsearchTemplate template;

/**
	 * 批量更新
	 * @param request
	 */
	public void updateQueryByField(Map<String,Map<String,String>> map) {
		List<UpdateQuery> queries = new ArrayList<>();
		Iterable<EsModel> list = esRepository.findAll();
		for(EsModel esmodel : list) {
			UpdateQuery query = new UpdateQuery();
			for (Map.Entry<String, Map<String,String>> entry : map.entrySet()) {
                String field = entry.getKey();
                String oldValue = "";
                String newValue = "";
                Map<String, String> value = (Map<String, String>) entry.getValue();
                	for (Map.Entry<String, String> map2 : value.entrySet()) {
                		oldValue = map2.getKey();
                		newValue = map2.getValue();
                	}
                String idOrCode = "ctx._source."+field;
                UpdateRequest updateRequest = new UpdateRequest();
                updateRequest.script(new Script(ScriptType.INLINE,
    					"painless",
			            "if("+idOrCode+"== "+"'"+oldValue+"'"+"){"+idOrCode+"= "+"'"+newValue+"'"+"}",
			            Collections.emptyMap()));
                query.setUpdateRequest(updateRequest);
                query.setIndexName("item");
    			query.setType("docs");
    			query.setId(esmodel.getId());
    			template.update(query);
    			//queries.add(query);
			}
		}
		//template.bulkUpdate(queries);
	}

注释:EsModel为实体类可自行定义

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "item",type = "docs", shards = 1, replicas = 0)
public class EsModel{
	@Id
	private String id;
	@Field(type = FieldType.Text, analyzer = "ik_max_word")
	private String title; //标题
	@Field(type = FieldType.Text, analyzer = "ik_max_word")   //不需要分词类型
	private String keyword;// 关键词
}

测试类如下:

@RequestMapping("updateQueryByField")
	public String updateQueryByField() {
		
		Map<String,Map<String,String>> map = new HashMap<String, Map<String,String>>();//key:字段名称,value:原值和待修改的值
		Map<String,String> mapValue = new HashMap<>();
		mapValue.put("张三1111", "张三111"); //key:原数据,value:待更新的新数据
		map.put("title", mapValue);
		
		Map<String,String> mapValue2 = new HashMap<>();
		mapValue2.put("王五1111", "王五111");
		map.put("keyword", mapValue2);
		
		esUtils.updateQueryByField(map);
		return "success";
	}

如果一次只更新一个字段的值,可以使用以下方法

/**
	 * 批量更新
	 */
	public void updateQueryByField2() {
		List<UpdateQuery> queries = new ArrayList<>();
		Iterable<EsModel> list = esRepository.findAll();
		String idOrCode = "ctx._source."+"title";
		for(EsModel esmodel : list) {
			UpdateQuery query = new UpdateQuery();
			UpdateRequest updateRequest = new UpdateRequest();
			updateRequest.script(new Script(ScriptType.INLINE,
					"painless",
				            "if("+idOrCode+"!= '张三111'){"+idOrCode+"= '张三111'}",
				            Collections.emptyMap()));
			query.setUpdateRequest(updateRequest);
			query.setIndexName("bdms3");
			query.setType("docs");
			query.setId(esmodel.getId());
			queries.add(query);
		}
		template.bulkUpdate(queries);
	}

以上是java方法实现es的批量更新。此外也可以使用kibana语句进行更新:

POST item/_update_by_query
{
  "script": {
    "lang": "painless",
    "inline": "if(ctx._source.title== '张三111'){ctx._source.title= '张三1111'}"
  }
}

期间也查阅了很多资料,可以参考如下博客:

https://blog.csdn.net/wwd0501/article/details/83274930

https://blog.csdn.net/zhou_shaowei/article/details/80079162

https://blog.csdn.net/zhou_shaowei/article/details/80078877

https://blog.csdn.net/pianpiannia/article/details/88944376

https://blog.csdn.net/wangh92/article/details/82854775

Spring Data Elasticsearch 提供了一种方便的方式来操作 Elasticsearch。下面是使用 Spring Data Elasticsearch4.1.0 操作复杂文档的教程。 1. 添加 Maven 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>4.1.0</version> </dependency> ``` 2. 创建实体类 创建一个实体类来表示 Elasticsearch 中的文档,例如: ```java @Document(indexName = "blog", createIndex = false) public class Blog { @Id private String id; @Field(type = FieldType.Keyword) private String title; @Field(type = FieldType.Text) private String content; @Field(type = FieldType.Date) private Date createTime; // getters and setters } ``` 在实体类上使用 `@Document` 注解来指定索引的名称,并使用 `@Field` 注解来指定每个字段的类型。 3. 创建 ElasticsearchRepository 创建一个 `ElasticsearchRepository` 接口,继承自 `org.springframework.data.elasticsearch.repository.ElasticsearchRepository` 接口,例如: ```java public interface BlogRepository extends ElasticsearchRepository<Blog, String> { List<Blog> findByTitleOrContent(String title, String content); List<Blog> findByCreateTimeBetween(Date start, Date end); } ``` `ElasticsearchRepository` 接口提供了许多常用的 Elasticsearch 操作方法,例如 `save`、`findById`、`delete` 等。在这个示例中,我们还定义了两个自定义查询方法。 4. 使用 ElasticsearchRepository 在代码中,可以使用 `BlogRepository` 对 Elasticsearch 进行操作,例如: ```java @Autowired private BlogRepository blogRepository; public void saveBlog(Blog blog) { blogRepository.save(blog); } public Blog getBlogById(String id) { Optional<Blog> optionalBlog = blogRepository.findById(id); return optionalBlog.orElse(null); } public List<Blog> searchBlogs(String keyword) { return blogRepository.findByTitleOrContent(keyword, keyword); } public List<Blog> getBlogsByCreateTime(Date start, Date end) { return blogRepository.findByCreateTimeBetween(start, end); } ``` 通过 `BlogRepository` 的方法可以操作 Elasticsearch 中的文档,例如保存文档、根据 ID 获取文档、搜索文档等。 以上就是使用 Spring Data Elasticsearch4.1.0 操作复杂文档的教程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值