How can I check `elasticsearch is down` condition in my service?

393 Views Asked by At

I have some service. I need return data from elastic search if it available or return from DB:

@Service
class DefaulUserService implements UserService {

    private final DbDao dbDao;
    private final ElasticsearchDao elasticsearchDao;

    DefaultDoctorService(DbDao dbDao, ElasticsearchDao elasticsearchDao) {
        this.dbDao= dbDao;
        this.elasticsearchDao= elasticsearchDao;
    }

    @Override
    public List<User> findAll() {
       if(elasticsearch is down){
             return dbDao.findAll();
        } else {
             return elasticsearchDao.findAll();
       }
    }
}

How can I check the elasticsearch is down condition in my service?

2

There are 2 best solutions below

4
On BEST ANSWER

If it's truly down, elasticsearchDao.findAll(); should surely raise an exception, right?

@Service
class DefaultUserService implements UserService {

    private final DbDao dbDao;
    private final ElasticsearchDao elasticsearchDao;

    DefaultDoctorService(DbDao dbDao, ElasticsearchDao elasticsearchDao) {
        this.dbDao= dbDao;
        this.elasticsearchDao= elasticsearchDao;
    }

    @Override
    public List<User> findAll() {
        try {
            return elasticsearchDao.findAll();
        }
        catch(Exception e) {
            return dbDao.findAll();
        }
    }
}

Obviously you'd have to pick a more appropriate type of exception to catch.

1
On

You can simply use the ES cluster health API and check it. it will not only check the uptime of ES, but the same API can be used to get the health status of only specified data streams and indices.

Few important statuses

  1. RED:- One or more primary shard missing.
  2. Yeloow:- One or more Replica shard missing.
  3. Green:- Everything fine :)