# Complex Query - Using retrieved documents for secondary query

**URL:** <https://discuss.elastic.co/t/complex-query-using-retrieved-documents-for-secondary-query/6363>\
**Category:** Elasticsearch\
**Created:** [January 12, 2012, 2:03pm UTC](https://discuss.elastic.co/t/complex-query-using-retrieved-documents-for-secondary-query/6363 "2012-01-12T14:03:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dkullmann](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dkullmann/32/2283_2.png) [@dkullmann](https://discuss.elastic.co/u/dkullmann)\
**Post date:** [January 12, 2012, 2:03pm UTC](https://discuss.elastic.co/t/complex-query-using-retrieved-documents-for-secondary-query/6363/1 "2012-01-12T14:03:58Z")

</div>

Hello,

I have one index with documents that represent property listings. My  
application finds property listings and provides visitors with  
information about how each property compares to similar properties  
nearby.

For example, let's say the user performed a search and these documents  
were returned: [https://gist.github.com/7ee990b3216977931b5d](https://gist.github.com/7ee990b3216977931b5d)

For the first document with id '10526-pace-ave-los-angeles-ca-90002' I  
would find similar properties that are nearby. A simple formula is  
used to find nearby properties that are also similar:

1. Restrict the geo\_distance to 1 mile from 10526-pace-ave-los-angeles-  
ca-90002
2. Only include properties with an equal number of bedrooms of the  
10526-pace-ave-los-angeles-ca-90002 document
3. Only include properties with +/- 1 bathroom of the 10526-pace-ave-  
los-angeles-ca-90002 document
4. Only include properties with +/- 10% square footage of the 10526-  
pace-ave-los-angeles-ca-90002 document

The second search only needs to return summary information, such as  
the average ListPrice for the found properties.

The same is repeated for all other documents ('10526-de-soto-avenue-  
chatsworth-ca-91311', etc.) so that each document has this  
information.

Right now if I do a primary search and it returns 20 documents, I have  
to do 20 additional searches for the similar properties. Is there a  
way to combine all of this into one request, perhaps using scripting  
or a more complex search?

Thanks,  
David

---

<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, 3:42am UTC](https://discuss.elastic.co/t/complex-query-using-retrieved-documents-for-secondary-query/6363/2 "2017-07-06T03:42:55Z")

</div>

Closed on July 6, 2017, 3:42am UTC


