# How to run optimize query query using Java API?

**URL:** <https://discuss.elastic.co/t/how-to-run-optimize-query-query-using-java-api/18915>\
**Category:** Elasticsearch\
**Created:** [July 26, 2014, 7:32pm UTC](https://discuss.elastic.co/t/how-to-run-optimize-query-query-using-java-api/18915 "2014-07-26T19:32:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sumit\_gupta\_sgt](https://avatars.discourse-cdn.com/v4/letter/s/dec6dc/32.png) [@sumit\_gupta\_sgt](https://discuss.elastic.co/u/sumit_gupta_sgt)\
**Post date:** [July 26, 2014, 7:32pm UTC](https://discuss.elastic.co/t/how-to-run-optimize-query-query-using-java-api/18915/1 "2014-07-26T19:32:27Z")

</div>

Hi,

I want to run optimize query on indexes using Java Api.  
Please suggest me how can i achieve this.

Thanks,  
Sumit Gupta

---

<div class="post-metadata">

**Author:** ![finominfo](https://avatars.discourse-cdn.com/v4/letter/f/82dd89/32.png) [@finominfo](https://discuss.elastic.co/u/finominfo)\
**Post date:** [July 28, 2014, 4:04pm UTC](https://discuss.elastic.co/t/how-to-run-optimize-query-query-using-java-api/18915/2 "2014-07-28T16:04:44Z")

</div>

The Optimize API  
The Optimize API invokes the segments merge process on the given  
indices. Just like  
the RESTful version of this API, we are allowed to set the target number  
of segments  
or only remove the deleted documents from the index. For example, the  
following  
code snippet executes the optimize operation on the library index,  
specifies that  
the maximum number of segments is 2. The flush should be performed after the  
operation and we are not only interested in removing the deleted documents:  
OptimizeResponse response = client.admin().indices()  
.prepareOptimize("library")  
.setMaxNumSegments(2)  
.setFlush(true)  
.setOnlyExpungeDeletes(false)  
.execute().actionGet();

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 6, 2017, 1:12am UTC](https://discuss.elastic.co/t/how-to-run-optimize-query-query-using-java-api/18915/3 "2017-07-06T01:12:46Z")

</div>


