Elasticsearch工作问题(一)
2024-06-20 11:53:34 # Elasticsearch # 问题总结

ES工作问题总结(一)

目录

比较两个字符串日期的值

问题

这里的问题是比较两个字符串日期的值,a>b时候能比较出count值,但是b<a的时候无法比较count的值。

解析问题

这里的问题是两个字段的格式是keyword类型,直接根据keyword类型比较没法比较出两个字段的大小
所以有下面有两种方案

问题解答

  1. 创建新索引,指定mapping这两个字段的类型为日期格式,将索引数据导入到新索引,然后删除旧索引,用新索引的字段类型进行比较

  2. 先将这两个字段转为日期类型再进行比较,但是每个字段都要转一下占用资源过大,除非是无法动原始数据的情况,否则不推荐,这里转成LocalDateTime再进行比较

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    GET /ods_all_dms_vehiclesold_di/_count
    {
    "query": {
    "bool": {
    "must_not": {
    "exists": {
    "field": "mileage"
    }
    },
    "must": [
    {
    "exists": {
    "field": "productiondate"
    }
    },
    {
    "range": {
    "invoicedate": {
    "gt": "1910-01-01 00:00:00",
    "format": "yyyy-MM-dd HH:mm:ss"
    }
    }
    },
    {
    "range": {
    "invoicedate": {
    "lt": "now"
    }
    }
    }
    ],
    "filter": [
    {
    "script": {
    "script": {
    "source": """
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss');
    LocalDateTime invoicedate = LocalDateTime.parse(doc['invoicedate'].value, formatter);
    LocalDateTime productiondate = LocalDateTime.parse(doc['productiondate'].value, formatter);
    return invoicedate.isAfter(productiondate);
    """,
    "lang": "painless"
    }
    }
    }
    ]
    }
    }
    }