# Dot product in Elastic Search

**URL:** <https://discuss.elastic.co/t/dot-product-in-elastic-search/31746>\
**Category:** Elasticsearch\
**Created:** [October 7, 2015, 5:33am UTC](https://discuss.elastic.co/t/dot-product-in-elastic-search/31746 "2015-10-07T05:33:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cuongvt101](https://avatars.discourse-cdn.com/v4/letter/c/dc4da7/32.png) [@cuongvt101](https://discuss.elastic.co/u/cuongvt101)\
**Post date:** [October 7, 2015, 5:33am UTC](https://discuss.elastic.co/t/dot-product-in-elastic-search/31746/1 "2015-10-07T05:33:21Z")

</div>

How can I do dot product in Elastic Search?

Let's say my indexed documents in the form:

```
{
   "name": "...",
   "features": [
      {"f_i": 0.xxx},
      ...
      {"f_j": 0.xxx}
   ]
}

```

For example, one document could be:

```
 {
           "name": "img1",
           "features": [
              {"f1": 0.6},
              {"f3": 0.4}
           ]
   }

```

Another document could be

```
 {
           "name": "img2",
           "features": [
              {"f2": 0.1},
              {"f3": 0.5},
              {"f5": 0.4}
           ]
   }

```

Basically, the features field of each document is a sparse vector where we only display the elements that have values \> 0. Assuming that we know the whole length of the sparse vector, let's say 100.

Now I want to query a new document to find the one in the index that has the most similar features, by which I measure by taking the dot product of 2 vectors. Say my query document is:

```
 {
           "name": "img",
           "features": [
              {"f3": 0.2},
              {"f4": 0.4},
              {"f5": 0.1},
              {"f6": 0.3}
           ]
   }

```

then the dot product with the 1st example above only happens at f3 so it is 0.4 x 0.2 = 0.08, while the dot product with the 2nd example above happens at f3 and f5 so it is 0.5 x 0.2 + 0.4 x 0.1 = 0.14. Thus the query would give higher score for 2nd document.

How do I do that? Thanks

P/S: I had another topic asking about searching for nearest neighbor in ES, now I figure out that that process should be done outside of ES, thus now the remaining problem can be stated clearer like this.

---

<div class="post-metadata">

**Author:** ![cuongvt101](https://avatars.discourse-cdn.com/v4/letter/c/dc4da7/32.png) [@cuongvt101](https://discuss.elastic.co/u/cuongvt101)\
**Post date:** [October 8, 2015, 3:49pm UTC](https://discuss.elastic.co/t/dot-product-in-elastic-search/31746/2 "2015-10-08T15:49:52Z")

</div>

Any idea would be greatly appreciated. Thanks a lot!

---

<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 5, 2017, 11:45pm UTC](https://discuss.elastic.co/t/dot-product-in-elastic-search/31746/3 "2017-07-05T23:45:51Z")

</div>


