elastic search6.2.2 实现搜索记录查询 ,类似新浪微博这种,同样的搜索记录后面时间点的会覆盖前面的(主要思路:关键词去重,然后按时间排序)
先创建索引
//我的搜索 PUT my_search { "settings":{ "number_of_replicas": 0 }, "mappings":{ "_doc":{ "properties":{ "user": {"type": "integer"}, "word": {"type": "keyword"}, "datetime": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" } } } } }
插入搜索记录
POST my_search/_doc // 自动生成ID { "user": 1, "word": "区块链", "datetime":"2018-02-08 23:58:59" } { "user": 1, "word": "刘平", "datetime":"2018-03-08 23:58:59" } { "user": 1, "word": "你好", "datetime":"2018-04-08 23:58:59" } { "user": 1, "word": "我好", "datetime":"2018-05-08 23:59:59" } { "user": 1, "word": "你好", "datetime":"2018-06-08 23:58:59" } { "user": 1, "word": "他好", "datetime":"2018-07-09 23:58:59" } { "user": 1, "word": "他好", "datetime":"2018-08-09 23:58:59" }
写入文档后的搜索记录可视界面(以按时间排序)
下面要读取出来了
POST my_search/_search // 我的最近搜索记录(展示10条) { "query":{ "match":{ "user":"1" } }, "aggs":{ "my_so":{ "terms":{ "field":"word", "size":10, "order":{ "max_time":"desc" } }, "aggs":{ "max_time":{ "max":{ "field":"datetime" } } } } }, "size":0, "from":0 }
搜索结果:
下面是网友总结的一些聚合排序方法: