# How do I write an ElasticSearch query to find unique elements in columns?

**URL:** <https://discuss.elastic.co/t/how-do-i-write-an-elasticsearch-query-to-find-unique-elements-in-columns/96361>\
**Category:** Elasticsearch\
**Created:** [August 9, 2017, 2:09am UTC](https://discuss.elastic.co/t/how-do-i-write-an-elasticsearch-query-to-find-unique-elements-in-columns/96361 "2017-08-09T02:09:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![TalKSicK333](https://avatars.discourse-cdn.com/v4/letter/t/71c47a/32.png) [@TalKSicK333](https://discuss.elastic.co/u/TalKSicK333)\
**Post date:** [August 9, 2017, 2:09am UTC](https://discuss.elastic.co/t/how-do-i-write-an-elasticsearch-query-to-find-unique-elements-in-columns/96361/1 "2017-08-09T02:09:18Z")

</div>

For example, if I have a SQL query:

SELECT distinct emp\_id, salary FROM TABLE\_EMPLOYEE  
what would be its ElasticSearch equivalent?

This is what I have come up with until now:

{  
"aggs": {  
"Employee": {  
"terms": {  
"field":["emp\_id", "salary"]  
"size": 1000  
}  
}  
}  
}

---

<div class="post-metadata">

**Author:** ![colings86](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/colings86/32/44960_2.png) [@colings86](https://discuss.elastic.co/u/colings86)\
**Post date:** [August 11, 2017, 9:46am UTC](https://discuss.elastic.co/t/how-do-i-write-an-elasticsearch-query-to-find-unique-elements-in-columns/96361/2 "2017-08-11T09:46:21Z")

</div>

You'll need a separate terms aggregation for each field here. Try the following instead:

```auto
{
	"aggs": {
		"Employee": {
			"terms": {
				"field": "emp_id"
				"size": 1000
			},
			"aggs": {
				Salary: {
					"terms": {
						"field":"salary"
						"size": 100
					}
				}
			}
		}
	}
}

```

Note that this is still slightly different from the SQL query you posted because it will give you the top 1000 employees ordered by doc\_count and for each employee the top 100 salaries ordered by doc\_count.

Hope that helps

---

<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:** [September 8, 2017, 9:47am UTC](https://discuss.elastic.co/t/how-do-i-write-an-elasticsearch-query-to-find-unique-elements-in-columns/96361/3 "2017-09-08T09:47:03Z")

</div>

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