If you're working in scala, a way to do this and use Future
's is to create a RequestExecutor, then use the IndicesStatsRequestBuilder and the administrative client to submit your request.
import org.elasticsearch.action.{ ActionRequestBuilder, ActionListener, ActionResponse }
import scala.concurrent.{ Future, Promise, blocking }
/** Convenice wrapper for creating RequestExecutors */
object RequestExecutor {
def apply[T <: ActionResponse](): RequestExecutor[T] = {
new RequestExecutor[T]
}
}
/** Wrapper to convert an ActionResponse into a scala Future
*
* @see http://chris-zen.github.io/software/2015/05/10/elasticsearch-with-scala-and-akka.html
*/
class RequestExecutor[T <: ActionResponse] extends ActionListener[T] {
private val promise = Promise[T]()
def onResponse(response: T) {
promise.success(response)
}
def onFailure(e: Throwable) {
promise.failure(e)
}
def execute[RB <: ActionRequestBuilder[_, T, _, _]](request: RB): Future[T] = {
blocking {
request.execute(this)
promise.future
}
}
}
The executor is lifted from this blog post which is definitely a good read if you're trying to query ES programmatically and not through curl. One you have this you can create a list of all indexes pretty easily like so:
def totalCountsByIndexName(): Future[List[(String, Long)]] = {
import scala.collection.JavaConverters._
val statsRequestBuider = new IndicesStatsRequestBuilder(client.admin().indices())
val futureStatResponse = RequestExecutor[IndicesStatsResponse].execute(statsRequestBuider)
futureStatResponse.map { indicesStatsResponse =>
indicesStatsResponse.getIndices().asScala.map {
case (k, indexStats) => {
val indexName = indexStats.getIndex()
val totalCount = indexStats.getTotal().getDocs().getCount()
(indexName, totalCount)
}
}.toList
}
}
client
is an instance of Client which can be a node or a transport client, whichever suits your needs. You'll also need to have an implicit ExecutionContext
in scope for this request. If you try to compile this code without it then you'll get a warning from the scala compiler on how to get that if you don't have one imported already.
I needed the document count, but if you really only need the names of the indices you can pull them from the keys of the map instead of from the IndexStats
:
indicesStatsResponse.getIndices().keySet()
This question shows up when you're searching for how to do this even if you're trying to do this programmatically, so I hope this helps anyone looking to do this in scala/java. Otherwise, curl users can just do as the top answer says and use
curl http://localhost:9200/_aliases
curl http://localhost:9200/_stats/indexes\?pretty\=1
– Deputation