# Index document only if it is unique by property

**URL:** <https://discuss.elastic.co/t/index-document-only-if-it-is-unique-by-property/100524>\
**Category:** Elasticsearch\
**Created:** [September 14, 2017, 11:48am UTC](https://discuss.elastic.co/t/index-document-only-if-it-is-unique-by-property/100524 "2017-09-14T11:48:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dbrezoev](https://avatars.discourse-cdn.com/v4/letter/d/8baadc/32.png) [@dbrezoev](https://discuss.elastic.co/u/dbrezoev)\
**Post date:** [September 14, 2017, 11:48am UTC](https://discuss.elastic.co/t/index-document-only-if-it-is-unique-by-property/100524/1 "2017-09-14T11:48:41Z")

</div>

Is there a way to index a document only if it is unique by property name for example.  
I already have read about the opType options, but they force me to use ID when I index a document, and I don`t know to. My goal is to write something like this:

```
elasticClient.index({
index: myIndex,
type: myType,
body: {name: 'TEST1', age: 42}

```

});

and if a document with name TEST1 already exists, this query to fail somehow.

---

<div class="post-metadata">

**Author:** ![mujtabahussain](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mujtabahussain/32/17514_2.png) [@mujtabahussain](https://discuss.elastic.co/u/mujtabahussain)\
**Post date:** [September 14, 2017, 11:57am UTC](https://discuss.elastic.co/t/index-document-only-if-it-is-unique-by-property/100524/2 "2017-09-14T11:57:37Z")

</div>

You can create the ID for the document using the `name` filed somehow! E.g.

Magical function `f(x) -> uuid`

`f("Gollum") -> 12345`  
`f("Smeagol") -> 12346`

So given data `d = {'name': 'TEST' ... }`, when you do an insert, you can use `_id: f(d['name'])` and if the `d['name']`field is duplicate the index will fail as the `_id` field has to be unique.

Mind you, this will only work for `index` operation, not `update`.

---

<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:** [October 12, 2017, 11:58am UTC](https://discuss.elastic.co/t/index-document-only-if-it-is-unique-by-property/100524/3 "2017-10-12T11:58:04Z")

</div>

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