【问题标题】:SQL query taking longer time to execute than expected time using Hibernate SQL Query使用 Hibernate SQL Query 执行 SQL 查询的时间比预期的要长
【发布时间】:2018-02-08 00:30:20
【问题描述】:

SQL 查询有时会变得难以处理。所以我有一个包含多个 OR 操作和 REGEX 的 SQL 查询。而通过 JAVA 代码运行的时间在庞大的数据条目上超过了预期的时间。

下面是查询:

SELECT * FROM tableName WHERE (col1 REGEXP ('xyz'|'abc') OR (col2 = 15 AND (col1 REGEXP ('xyz'|'abc')))) AND col3>='2017-08-28' AND col3<='2017-08-30';

休眠代码:

public List<MyModel> getAllMatchedEntries() {
        long lStartTime = new Date().getTime();
        Query query = ((SQLQuery) getSession().createSQLQuery( "SELECT * FROM tableName WHERE (col1 REGEXP :list OR (col2 = 15 AND (col1 REGEXP :list))) AND col3>=:sd AND col3<=:ed"). setResultTransformer(Transformers.aliasToBean(LeadGenViewTable.class)).setParameter("list", regexlist).setParameter("mid", merchant_id).setParameter("todayDate", sd).setParameter("ed", ed));
        List<MyModel> list = query.list();
        long lEndTime = new Date().getTime();
        long output = lEndTime - lStartTime;
        list= list.stream().filter(distinctByKey(t -> t.getSomeCol())).collect(Collectors.toList());
        System.out.println("Time Taken "+output);
        return list;
    }

出人意料地在日志中输出:

Time Taken 45616

由于 REGEXP / OR 操作,我很难弄清楚发生的时间延迟。帮助将不胜感激。

【问题讨论】:

  • 运行EXPLAIN,它可能会为查询完成的数据过滤提供一些输入。您也可以尝试将BETWEEN 用于col3 条件。
  • 您是如何计算预期时间的?您是否直接对数据库运行完全相同的查询?如果你使用 hibernate,你永远不必编写一个普通的 sql 查询
  • @XtremeBaumer 请检查更新的问题。是的,运行相同的查询会在 2 秒内对相同的数据给出结果。编写普通 sql 查询的原因是正则表达式,因为我找不到使用条件或 hql 实现正则表达式的最佳方法。
  • @AnkitaGoyal this is a solution 这可能有效。 another example 或者你扩展你的方言像this

标签: java mysql sql hibernate


【解决方案1】:
(col1 REGEXP :list OR (col2 = 15 AND (col1 REGEXP :list)))

相同
(col1 REGEXP :list)

col3上有一个索引

而正则表达式通常可以更好地重写 - 然后利用索引:

col1 REGEXP ('xyz'|'abc')
col1 IN ('xyz', 'abc')
(col1 = 'xyz' OR col1 = 'abc')

对于 IN 版本,可以使用 java.sql.Array 作为参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多