---
title: "es一致性问题"
author: "fireinwind"
date: "2016-08-17T20:07:59Z"
tags: []
categories: ["开源软件"]
slug: "es"
draft: false
lastmod: "2016-08-17T20:07:59Z"
id: 2318058
url: "https://fireinwind.iteye.com/blog/2318058"
---

https://segmentfault.com/a/1190000005844120

 

## 概述

### 内部因素

es的一致性主要有两个方面：

- 使用lucene索引机制带来的refresh问题
- 使用分片和复制带来的副本一致性问题(`consistency：one、all、quorum`)

### 外部因素

外部因素的话，就是如果使用db跟es的同步机制的话，那么这里的同步有一定的延时，另外也有可能因为异常情况发生不一致的情况，比如事务回滚之类的。

## 更新操作之后refresh

org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository

```
@Override
    public <S extends T> S save(S entity) {
        Assert.notNull(entity, "Cannot save 'null' entity.");
        elasticsearchOperations.index(createIndexQuery(entity));
        elasticsearchOperations.refresh(entityInformation.getIndexName());
        return entity;
    }

    public <S extends T> List<S> save(List<S> entities) {
        Assert.notNull(entities, "Cannot insert 'null' as a List.");
        Assert.notEmpty(entities, "Cannot insert empty List.");
        List<IndexQuery> queries = new ArrayList<IndexQuery>();
        for (S s : entities) {
            queries.add(createIndexQuery(s));
        }
        elasticsearchOperations.bulkIndex(queries);
        elasticsearchOperations.refresh(entityInformation.getIndexName());
        return entities;
    }
```

一旦有更改就refresh到filesystem cache，这样就可以被搜索到。

![](https://segmentfault.com/img/bVyG1s)

## 副本一致性问题

但是还有一个问题，一旦有多个replication，就涉及到一致性的问题。

- 如果consistency是one，那么写入速度快，不能保证读到最新的更改；
- 如果是quorum则是相对折中的版本，write的时候，W&gt;N/2，即参与写入操作的节点数W，必须超过副本节点数N的一半。如果是quorum策略，则读取要保证一致性的话，就得使用read quorum，读取N个副本中的W个然后仲裁得到最新数据。或者是指定从primary上面去读。  
  相关的类

```
org/elasticsearch/action/WriteConsistencyLevel.java
org/elasticsearch/action/RealtimeRequest.java
```

- realtime request  
  es提供了realtime request，就是从translog里头读，可以保证是最新的。

```
public class GetRequest extends SingleShardRequest<GetRequest> implements RealtimeRequest {
  //......
}
```

但是注意get是最新的，但是检索等其他方法不是(`如果需要搜索出来也是最新的，需要refresh，这个会刷新该shard但不是整个index，因此如果read请求分发到repliac shard，那么可能读到的不是最新的数据，这个时候就需要指定preference=_primary`)。

![](https://segmentfault.com/img/bVyHom)

- all策略即强一致的策略

## 小结

如果要保证读的强一致：

- 当write consistency不是all的时候，需要指定从primary shard读
- 当write consistency为all的时候，而且replication是sync模式(默认)，无需额外指定，如果replication是async模式，则需要从primary shard读取。

```
curl -XGET 192.168.99.100:9200/myindex/_settings

curl -XPUT '192.168.99.100:9200/myindex/_settings' -d '
{
    "index" : {
        "action.write_consistency" : "all"
    }
}'
```

但是都需要在update的时候手工refresh。

如果是读多写少的应用(特别是replica不多的时候)，则可以指定write consistency为all，这样就可以很好地利用replica shard的读来提升es的读性能呢。

 

## 参考

- [distrib-write](https://www.elastic.co/guide/en/elasticsearch/guide/2.x/distrib-write.html)
- [RWN及Quorum与强一致性](https://segmentfault.com/a/1190000004499551)
- [get-consistency-and-quorum-in-elasticsearch](https://discuss.elastic.co/t/get-consistency-and-quorum-in-elasticsearch/10201)
- [Write Consistency Level for index/delete/delete\_by\_query/bulk with one/quorum/all. Defaults to quorum.](https://github.com/elastic/elasticsearch/issues/444)
- [search-request-preference](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-preference.html)
- [Question on read consistency](https://groups.google.com/forum/#!topic/elasticsearch/mk3uqJQXCxM)
- [read-write-consistency](http://grokbase.com/t/gg/elasticsearch/144wfjhp31/read-write-consistency)