# Calculate k Nearest Neighbours using Cosine Similarity

**URL:** <https://discuss.elastic.co/t/calculate-k-nearest-neighbours-using-cosine-similarity/116647>\
**Category:** Elasticsearch\
**Created:** [January 23, 2018, 10:35am UTC](https://discuss.elastic.co/t/calculate-k-nearest-neighbours-using-cosine-similarity/116647 "2018-01-23T10:35:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vaibhav\_Rathi](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/vaibhav_rathi/32/26833_2.png) [@Vaibhav\_Rathi](https://discuss.elastic.co/u/Vaibhav_Rathi)\
**Post date:** [January 23, 2018, 10:35am UTC](https://discuss.elastic.co/t/calculate-k-nearest-neighbours-using-cosine-similarity/116647/1 "2018-01-23T10:35:58Z")

</div>

Hi,

I am trying to calculate the K Nearest Neighbours of a Vector at querytime.  
I have structured my data as Follows:

{  
"vector": [  
0,  
0,  
0,  
0.3004656841866144,  
0.028906494022773094,  
0,  
0.001937984496124031,  
0.051182667461737226,  
0,  
0.001937984496124031,  
0.003875968992248062,  
0,  
0,  
0.007751937984496124,  
0.001937984496124031,  
0.5068361870687452,  
0.06256921373200443,  
0,  
0.032597893063009344,  
0  
],  
"id": "79583a25d73cb2e82acaf29cdeb28b85"  
}

And I have an input vector as:  
[  
0,  
0.0014124293785310737,  
0,  
0.41034832330964105,  
0,  
0,  
0,  
0.004237288135593221,  
0,  
0.0014124293785310737,  
0,  
0,  
0,  
0.2172134135228723,  
0.04737903225806452,  
0,  
0.008474576271186442,  
0,  
0.29198104610898495,  
0.017541461636595593  
]

My Requirement is to get the nearest neighbours to the input vectors based on Cosine Similarity. I am working on Elasticsearch 6.0.0. I have about a million vector records out of which I have to pick the nearest neighbours.

Any help is appreciated.

Thanks in Advance!

---

<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 20, 2018, 10:36am UTC](https://discuss.elastic.co/t/calculate-k-nearest-neighbours-using-cosine-similarity/116647/2 "2018-02-20T10:36:04Z")

</div>

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