Distinct field values for a search condition

elastic search query , I need to get unqiue results. I have documents with below mapping.

   "appId": {
                    "type": "text"
                },
                "date": {
                    "type": "date"
                },
                "search": {
                    "type": "keyword"
                },
                "type": {
                    "type": "keyword"
                },
                "userId": {
                    "type": "text"
                }

I need to query on userId and search result should have unique combination of search and type feilds and should display only latest date result.
dedup is giving count but not distinct results.

Sample data:
{

            "_source": {
                "date": "2017-10-23T16:43:59.757Z",
                "appId": "xxx",
                "search": "$0",
                "type": "lenient",
                "userId": "USER1234"
            }
        },
        {
           
            "_source": {
                "date": "2017-10-23T17:30:06.544Z",
                "appId": "xxx",
                "search": "RAVI",
                "type": "index",
                "userId": "USER1234"
            }
        },
        {
           
            "_source": {
                "date": "2017-10-23T16:48:16.779Z",
                "appId": "xxx",
                "search": "$0",
                "type": "lenient",
                "userId": "USER124"
            }
        },
        {
            
            "_source": {
                "date": "2017-10-23T17:29:55.993Z",
                "appId": "xxx",
                "search": "RAVI",
                "type": "index",
                "userId": "USER1234"
            }
        },
         {
            "_source": {
                "date": "2017-10-23T17:29:55.993Z",
                "appId": "xxx",
                "search": "RAVI",
                "type": "index_mtnsummary",
                "userId": "2560559ADKV"
            }
        }

when searched for userid USER1234, query should display only below latest date records.
( select distinct search ,type from xxxindex where userID='USER1234')
{

            "_source": {
                "date": "2017-10-23T17:30:06.544Z",
                "appId": "xxx",
                "search": "RAVI",
                "type": "index",
                "userId": "USER1234"
            }
        },
        {
           
            "_source": {
                "date": "2017-10-23T16:48:16.779Z",
                "appId": "xxx",
                "search": "$0",
                "type": "lenient",
                "userId": "USER124"
            }
        }

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