How to auto-complete a value without overloading the database

Asked

Viewed 42 times

1

Well, I’m working with a table with a little over 60,000 records and a situation has arisen in which, through an input the user can search some text that contains in a record. Initially the user just typed the text to be searched and pressed the search button to carry out the filter, but now a need has arisen, while the user type appear a previous list with 10 results related to the text he typed in the input.

I imagine that going through the query while the user type would not also be a viable alternative, since, will generate a lot of requests overloading the server.

In some situations I had to do this with a smaller table, I simply brought this list ready as an array and was already filtering through this array to show this result preview to the user, but with this larger base I no longer know if this solution would be viable.

Explained the context, there is some "ready-made solution" for cases like this?

I’m using Mysql database, php with the Lumen framework as backend, Reactjs on the front and making requests via Xios.

  • If you are going to use my code, note that I had made a mistake. I have updated now. I forgot to tell you, but there are several libraries that implement this, if you want you can get a ready implementation.

  • @bfavaretto I wanted to have one more idea of how this is done without weighing the same server, I ended up finding some libraries to meet this situation, but I will end up implementing one myself. Thanks for the clarification! :)

1 answer

1


In such cases, what is done is to limit the amount of requests to the server. The traditional technique for this is the debauchery of the events of keyup of the browser in the search input. Instead of sending a new request to each keyup (which would be a waste of resources on both the server and browser), you send only in the last keyup of the sequence.

To implement this, you schedule the dispatch of the request for the near future, for example 500ms. If before this time the event occurs again, you replace this schedule with a new request based on the new event.

Example of implementation:

const intervalo = 500;
let timer, anterior;

function trataKeyup(e) {
    const agora = Date.now();
    if(agora - anterior < intervalo) {
        // Anula agendamento anterior
        clearTimeout(timer);
    }
    // Agenda nova requisição
    const val = e.target.value;
    timer = setTimeout( geraBuscaPor(val), intervalo );
    anterior = agora;    
}

function geraBuscaPor(valor) {
    return function() {
        axios.get('/?q=' + encodeURIComponent(valor)); 
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.