Search a Database

Quick database search question: I just got accepted to Wix Code yesterday and I was able to successfully build a database and accompanying dynamic page today, no problem. Love that!

Here is my question: Does anyone know of a youtube or Wix tutorial that shows you how to set up a page for user input to SEARCH the database (and thus direct you to the resulting dynamic page)? I assume I will have to use custom code for this, but I was hoping that someone had done a demo, walking us through the process.

I need my users to be able to input the physical issue they are experiencing into a search field and have the database then return the answer that goes with that matching physical issue.

7 Likes

Hi,

The way I would approach this involves some coding. Lets explore…

We’ll set up a search page with a search input (a regular text input), a button and a table for results. If your collection has item pages, We’ll set the table to link to the item pages. We do not connect any of the elements to a dataset.

In the button onClick event we perform the actual search. The code looks something like the following

import wixData from 'wix-data';
export function searchButton_onClick(event) {
  wixData.query('my-collection')
    .contains('physicalIssue', $w('#searchButton').value)
    .find()
    .then(res => {
      $w('#resultsTable').rows = res.items;
    });
}

The result of this is that we search for the value the user enters into the search input using a contains predicate - if the physicalIssue field includes the searched value, we will get it in the table.

In some cases, we may wish to search for items that may have any of the words in the search string. For instance, the search above, given ‘red car’ will only find items that have the phrase ‘red car’ in them. If we wish to find items that may have ‘red’ or ‘car’ in them, we can do the following -

import wixData from 'wix-data'; 
export function searchButton_onClick(event) {   
  let searchValue = $w('#searchButton').value;
  let searchWords = searchValue.split(' ');
  let query = wixData.query('my-collection')  
    .contains('physicalIssue', searchWords[0]);
    
  for (let i=1; i < searchWords.length; i++) {
    query = query.or(wixData.query('my-collection')
      .contains('physicalIssue', searchWords[i]));
  }  
      
  query.find() 
    .then(res => {  
      $w('#resultsTable').rows = res.items; 
    });
}
14 Likes

Oh my gosh! Thank you so much! This was so much more than I even asked for! I will work on this and let you know if I am successful! Thank you, thank you!!

1 Like

Thank you Walkingbillboards for asking this question as we too where shooting for the same solution. Yoav - would this work in a way that you that you search for in a normal directory like superpages dot com?

Hay D Koder,

superpages.com and google.com search is what is called Full Text Search (FTS) which involves some configuration, like how to index your data, how to tokenize, what stop words to use etc. What we show here is a database filter by for a phrase or words.

One thing we are looking at is what kind of searches are you looking to do? Database filters? Full Text Search? How do you envision it working?

1 Like

Yoav. thank you for the answer. I was looking for the same solution.
Although, it doesn’t seem to find any result and output them to the table result. Should I configure the table in any way? Is there a way to debug the java script?

Hi Navit,

Are you using the right field key? You can find the field key in the content manager (database view) in field properties (right click a field header, select field properties).

Hi I seem to have the same issue as Navit where the button looks to be working as the table returns column lines but no data. I have checked the field key as you suggested and this is correct. I am using the tables from user input is this correct?

Hi Mark,
yes, this is correct.
if you’re not getting any data, I suggest you submit the code snippet you’re using, and a screenshot of you collection with some data.
we’ll be able to help :wink:

2 Likes

It’s amazing to have this level of support. Thankyou!

3 Likes

As much as I love you guys (Ziv & Yoav), lol, I have tried & tried to decipher this (simple) code yet I have not been successful. Let me explain why (and what I mean) …

(1) “We’ll set up a search page with text input, button, and table for results” - DONE! I got this part. But that’s about it.

(2) “If your collection has item pages, We’ll set the table to link to the item pages.” - HOW? Do you mean something in the code you provided performs this ‘linking’ (can you please point it out), OR do you mean we should be changing the settings on the table somehow (because maybe it was in an article we should have read already)? I do not understand HOW the table and the item pages are linked together.

(3) “We do not connect any of the elements to a dataset.” Got it!

(4) The code …

There are sooooo many articles with exact code examples, just like the one above, for us to use. Now remember — 99% (or maybe slightly less) of the designers on here have ZERO (absolutely ZERO) knowledge of what even a FIELD KEY is, or means, or “looks” like. Most (like me) also don’t know WHAT part of the code needs to be ‘edited’ to match OUR fields/elements on OUR page.

Now … me … I am ASSUMING that somewhere in those green colored letters I probably should be typing in something from MY page. But WHERE do i get that something. I don’t know.

When I activated the Properties Panel, and started playing with the names and blank spaces under “Events” … (or anything that I changed, basically) … suddenly code started to appear at the bottom of my page … Why? lol ---- I don’t know. But I again, assumed, I was supposed to delete it. So I did.

I appreciate that Wix employees are giving us the "exact code’ for specific requests/functions we (designers) are looking for. But when we have a lot of “i don’t know’s” ----- It kind of discourages us from trying any further. (And that’s how you get the designers that say things like “Well why doesn’t Wix just MAKE the search button so WE don’t have to figure it out”)

I don’t want WIX to build the button FOR me. I want to LEARN how to do it myself. But … I feel there is a lot of missing information simply because as developers … you think like developers … and not teachers.

Conclusion to my story (sorry so long), can someone please guide me and explain where to get the data to fill in that code to customize it? (Pictures help …a LOT ---- that’s why I created videos for others to use because they couldn’t understand Text. Designers … visual learners … who’d of thunk it. LOL.)

Thank you. <3

8 Likes

Hi Nayeli,
thanks for this - we read you loud & clear - and are working on improving our assets to that beginners can be much more successful.

your post is exactly what we need to learn and improve.

I will post a reply here later today (meaning tonight sigh ;-)) with hopefully a clearer explanation.

thanks.

p.s.
your mindset is exactly right - you are trying to learn to be independent with wix code.
keep it up!!!

5 Likes

Nayeli, I made the same exact point about visual learners on my feedback call with Wix the other day. And I found them to be really receptive and I did see that they are gradually adding more tutorial videos as opposed to just articles for those of us who understand best when we SEE it. Thanks for your honesty and your post. You aren’t alone!

3 Likes

here’s a first attempt to make it clearer.
I added a lot of comments to the code snippet that searches for a value in a specific field.
Nayeli - let me know if this is in the right direction or not.

//this code should be in your search page
import wixData from 'wix-data';

//this code runs when the user clicks the search button.
//the code performs a wix-data query and returns results,
//then it passes the results to a table component.

//assumptions:
//1. the collection you want to search is named 'my-collection'. 
//   replace 'my-collection' with the name of the collection you want to search.

//2. the field in the collection you want to search in is named 'field1'.
//   replace 'field1' with the name of the field you want to search in.
//   note! you need to replace it with the *field Key* of your field.
//   you can find your field's key in the Content Manager by:
//   - hovering over the field in the topmost row
//   - clicking the three dots and choosing 'manage properties'

//3. your search button's ID is 'searchButton'.
//   replace it with the button's ID in your page.
//   you can see the button's ID in the properties panel when the button is selected.

//4. you have a table component called 'resultsTable'
//   replace it with the ID of your table component.

//5. your search input component's ID is 'searchInput'
//   replace it with the ID of your search input component.

export function searchButton_onClick(event) {
     //create a variable that will hold the search value.
     //get that value from the search input component.
     let searchValue = $w('#searchInput').value;
     
     //build a query for the 'my-collection' collection
     wixData.query('my-collection')
        //add a 'contains' condition to the query.
        //have the query look in the 'field1' field.
        //instruct it to look for the search value the user typed.
        .contains('field1', searchValue)
        
        //actually run the query
        .find()
        
        //when the query returns:
        .then(res => 
        {
            //get the items found from the result set 
            //place the results in a variable called 'foundItems'
            let foundItems = res.items;
            
            //now find the table component and make it display the results.
            $w('#resultsTable').rows = res.items;
        });
}


11 Likes

wooooooooow!!! this is WAY more than i expected … .diving in and reading it right now! excited!! (now get some rest … :slight_smile: hehehe )

1 Like

Ziv, this is great. A couple of nuggests that I think I was missing. Will see if I can make my search work now,

Thanks, Ziv! I am working on the page that needs the search site tonight and tomorrow so I will see if I can make it work with this latest post. Thanks again!

Following is my code, using the example.

It gets this error code when I run it in Preview.
There was an error in your script
TypeError: e is not a function. (In ‘e()’, ‘e’ is null)

It does not filter/query the data in the table is populated as it has been. Wondering if I need to unconnect the table from the dataset on the page? but then not sure how it’ll know what fields in which columns.

No errors show up in the console in the editor.

//For full API documentation, including code examples visit http://wix.to/94BuAAs
import {
wixData
}
from ‘wix-data’;

$w.onReady(function () {
//TODO: write your page related code here…
});

export function button1_onClick(event)
{
let searchValue = $w(‘#textInput1’).value;

 //build a query for the 'my-collection' collection 
 wixData.query('classmates') 
    //add a 'contains' condition to the query. 
    //have the query look in the 'field1' field. 
    //instruct it to look for the search value the user typed. 
    .contains('title', searchValue) 
    
    //actually run the query 
    .find() 
    .then(res =>  
    { 
		let foundItems = res.items; 

		//now find the table component and make it display the results. 
		$w('#table1').rows = res.items; 
	});
1 Like

Ok, for you … because i could not make it work :slight_smile:

I removed all ‘member’ permissions from pages and database collection in case you wanted to visit the live page. This is not a ‘real’ site. It is simply the site I use for the video tutorials I make. (So don’t try clicking on many ‘links’, they probably won’t go anywhere. :smiley:

https://webixdesigns.wixsite.com/cake/search

Hay Nayeli,

Looking at your site (I’ve opened it in the editor) the page code is

//For full API documentation, including code examples visit http://wix.to/94BuAAs

$w.onReady(function () {
	//TODO: import wixData from 'wix-data';
export function searchButton_onClick(event) {
  wixData.query('ClientDatabase')
    .contains('name', $w('#textInput1').value)
    .find()
    .then(res => {
      $w('#resultsTable').rows = res.items;
    });
}

And when clicking preview, we get the following messages:

public/pages/v7tsx.js: 'import' and 'export' may only appear at the top level (5:0) 3 | $w.onReady(function () { 4 | //TODO: import wixData from 'wix-data'; > 5 | export function searchButton_onClick(event) { | ^ 6 | wixData.query('ClientDatabase') 7 | .contains('name', $w('#textInput1').value) 8 | .find()
There was an error in your script
TypeError: e is not a function

The first line tells us there is an error in the page code - the export statement on the 5th line is out of place. It should appear on the top level - meaning, outside of any brackets (any ‘{’ and ‘}’ pair).

You can also see the same information by hovering over the red indication by line number 5


The second red dot tells us that wix-data is not defined - because we had not imported it yet.

The fix is quite simple. Just move the export function code out of the onReady code block and import wix data. It should look like

import wixData from 'wix-data';
//For full API documentation, including code examples visit http://wix.to/94BuAAs

$w.onReady(function () { 
  //TODO: import wixData from 'wix-data'; 
});

export function searchButton_onClick(event) {   
  wixData.query('ClientDatabase')
   .contains('name', $w('#textInput1').value)
   .find()
   .then(res => {   
      $w('#resultsTable').rows = res.items; 
    });
} 
3 Likes