mysql: efficient way for postfix-search (like '%text' aka. prefix wildcard)?

后端 未结 2 1863
庸人自扰
庸人自扰 2020-12-31 19:21

Is there any build-in functionality in MySQL to do the above without scanning the entire table?

Only solution I found is to store a mirrored version of the column I

相关标签:
2条回答
  • 2020-12-31 19:27

    A index over reverse field will be the solution, some think like:

    create index idx_reverse on table ( reverse( field ) );
    select * from table where reverse(field) like 'txet%';
    

    but MySQL don't alow index over expressions, only over columns:

    this is MySQL create index syntax:

    CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
        [index_type]
        ON tbl_name (index_col_name,...)
        [index_option] ...
    

    This is postgres create index syntax:

    CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] name ON table [ USING method ]
        ( { column | ( expression ) } [ opclass ] [, ...] )
        ...
    

    A work around may be create indexed second field (field -> dleif) and a mysql trigger to keep reversed field:

    alter table my_table add column dleif ...;
    create index idx_reverse on my_table ( dleif );
    Create Trigger `reverse_field` Before Update on `my_table` for each row BEGIN
        set new.dleif = reverse( new.field );
    END;
    select * from table where dleif like reverse('%text');
    
    0 讨论(0)
  • 2020-12-31 19:31

    MySQL won't use an index when your value starts with a wildcard character.

    Storing a second column in reverse order is a defensible approach. It will fail on a suffix, though.

    If you know the compounded words, you can pre-compute "valuable to know" matches and store them in another table. I think that's unlikely to work well for a German dictionary, but you might know something I don't.

    0 讨论(0)
提交回复
热议问题