# How to compare two documents from two different indexes using script

**URL:** <https://discuss.elastic.co/t/how-to-compare-two-documents-from-two-different-indexes-using-script/217047>\
**Category:** Elasticsearch\
**Created:** [January 29, 2020, 5:08pm UTC](https://discuss.elastic.co/t/how-to-compare-two-documents-from-two-different-indexes-using-script/217047 "2020-01-29T17:08:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![JBone](https://avatars.discourse-cdn.com/v4/letter/j/58f4c7/32.png) [@JBone](https://discuss.elastic.co/u/JBone)\
**Post date:** [January 29, 2020, 5:08pm UTC](https://discuss.elastic.co/t/how-to-compare-two-documents-from-two-different-indexes-using-script/217047/1 "2020-01-29T17:08:04Z")

</div>

Hi, I am searching for similar fields in two different indexes. My goal is to if those fields match, then I know there is a correlation between those two documents.

I do search first with accountNumber, and I group them with another identifier, so that is the reason I am doing what I am doing in aggregations. this is just a part of that bigger query.

For example, in Index A1

> {  
> "\_id": 1,  
> "refNumber": 123  
> "uID": 456  
> }

and in index B2

> {  
> "\_id": 1,  
> "refNumber": 6456456,  
> "uId": 123  
> }

So in the above two documents, the 'refNumber' in A1 index is equal to "uId" in the document with index B2. So here is what I am trying

> GET/A1, B2/\_search  
> {  
> "size": 0,  
> "aggs": {  
> "correlatedDocuments: {  
> "terms": {  
> "script": {  
> "source": "if(doc['A1.refNumber.keyword'].value == doc['B2.uId.keyword].value ) { return 1}"  
> }  
> }  
> }  
> }  
> }

obviously that does not work. How to solve this kind of problem? it does not have to be Painless script. I just want to connect the documents based on those two key values in two different indexes.

The data remodeling is not an option. May be if I find a solution that needs a change, then I can push for the change but is not an easy task.

Any help would be appreciated

---

<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:** [February 26, 2020, 5:08pm UTC](https://discuss.elastic.co/t/how-to-compare-two-documents-from-two-different-indexes-using-script/217047/2 "2020-02-26T17:08:06Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
