7

The almost comprehensive list of resources for developers to evaluate Algolia

 2 years ago
source link: https://www.algolia.com/blog/product/the-comprehensive-list-of-resources-for-developers-to-evaluate-algolia/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Comprehensive list of resources for developers to evaluate Algolia
zxjqqm5kzysjefjaavwi.jpg

While answering Algolia forum posts last week, I did a deep dive on Optional Filters for Algolia Search. Similar to filters and facet filters, optional filters are applied at query-time, allowing you to use all sorts of contextual information to improve results. Unlike the other filters, optional filters don’t remove records from the result set. Instead, they allow you to say, “If records match this filter, then move them up or down the ranking,” without changing the number of records returned. Some interesting use cases: Move posts that mention a particular user to the top of the result set Up-rank products available at a customer’s local store Down-rank products that are out-of-stock Pin a specific record to the top of the listing based on an external recommendations engine You can use filters and facet filters to reduce the number of records in the result set at query-time, then optional filters to manipulate the rankings for the remaining records. You can even apply filter scoring to control the order of the records further. Here’s an example that applies facet filters for product_type and price_range to an index from a Shopify store. The code selects the objectID of two records to promote, then injects them as optional filters into the query. If either of those products is part of the result set that matches the other criteria in the query, those products are pushed to the top of the ranking. The code uses filter scoring to ensure the featuredProduct will always appear above the alternateProduct. JavaScript import algoliasearch from 'algoliasearch'; const featuredProduct = '41469303161004'; const alternateProduct = '41469346644140'; const client = algoliasearch('H2M6B61JEG', 'b1bdfc3258823bb4468815a664dce649'); // Standard replica const index = client.initIndex('shopify_algolia_products_price_asc_standard'); // with params index.search(query, { facetFilters: [[ "product_type:HardGood", "price_range:75:100" ]], optionalFilters: [[ `objectID:${featuredProduct}<score=500>`, `objectID:${alternateProduct}<score=200>` ]], hitsPerPage: 50, }).then(({ hits }) => { console.log(hits.map(item => `- ${item.title} | ${item.product_type} | ${item.objectID} | ${item.price_range}`).join('\n')); }); 123456789101112131415161718192021222324 import algoliasearch from 'algoliasearch'; const featuredProduct = '41469303161004';const alternateProduct = '41469346644140'; const client = algoliasearch('H2M6B61JEG', 'b1bdfc3258823bb4468815a664dce649'); // Standard replicaconst index = client.initIndex('shopify_algolia_products_price_asc_standard'); // with paramsindex.search(query, {    facetFilters: [[        "product_type:HardGood",        "price_range:75:100"    ]],    optionalFilters: [[        `objectID:${featuredProduct}<score=500>`,        `objectID:${alternateProduct}<score=200>`    ]],    hitsPerPage: 50,}).then(({ hits }) => {    console.log(hits.map(item => `- ${item.title} | ${item.product_type} | ${item.objectID} | ${item.price_range}`).join('\n'));}); Notice that this code uses a standard replica of the Shopify index sorted by price. Optional filters don’t play well with Virtual Replica indices since both re-rank records at query-time, leading to unpredictable results. If you plan to use optional filters, you should use a standard replica that applies ranking at index-time. You can also use negative optional filters to push records down the ranking. For example, if you wanted to push posts written by the current user lower in the rankings but not remove them completely: JavaScript index.search('', { filters: `date_timestamp > ${Math.floor(d.setDate(d.getDate() - 7) / 1000)}`, optionalFilters: [ `author:-${user.name}` ], hitsPerPage: 50, }).then(({ hits }) => { console.log(hits}; }); 123456789 index.search('', {    filters: `date_timestamp > ${Math.floor(d.setDate(d.getDate() - 7) / 1000)}`,    optionalFilters: [      `author:-${user.name}`    ],    hitsPerPage: 50,}).then(({ hits }) => {    console.log(hits};}); Optional filters are a powerful tool to add to your ranking tool belt, but remember that any query-time calculations will impact search performance. For instance, you shouldn’t use filter scoring on searches that may return more than 100,000 results. Always try to move ranking criteria to index configuration when possible. Use optional filters only when you need to further tune your results at query-time using more real-time context. Let me know if you find a great (or not so great) use case for optional filters in your search UI!

yu1qatuyew4bswkle1yt.png
Engineering

Simplifying Tailwind CSS with ESLint tools, tagged template literals, and a lot more

After years of development, we decided to standardize the UI of one of our most important products – our multi-application dashboard. We did this for our customers and internal users (ease of use) as well as our product team (easier design process, decision-making, and coding). We also needed to align more consistently with our company’s branding.  For this, we built an internal design system, called Satellite. In developing Satellite, we looked at different CSS solutions for the UI library, all with their pros and cons: Saas, css modules, css-in-js. We settled on Tailwind CSS. Why?

Pure CSS (no JS runtime) – good for performance Tends to generate smaller CSS files (after purging) – also good for performance No switching between a CSS file and your javascript file while developing new components No time wasted trying to find good names for classes Helps promote UI consistency Allows you to define a collection of spacings and colors that map well to design tokens (a “Restricted Palette”)

However… there was a downside to Tailwind: the readability of complex components. The soup of Tailwind can be hard to digest when you’re not used to its classnames. In our case, it was made worse because we had to use a prefixed versions of the classes (stl-) to avoid conflicts with our legacy CSS, adding even more noise and length to our classname strings.  This article shows how we mitigated the readability problem. For starters, we used several techniques, such as tagged literals and interpolation, to shorten the length of our strings. Then we simplified the usage of the classnames with ESLint, providing a better DX with two tools:

An ESLint plugin, because there was no official ESLint-Tailwind plugin at the time.  A Visual Studio Code extension to simplify the usage by providing intellisense of Tailwind’s many classes. The official ESLint VS extension didn’t work for us because it expected a tailwind.config.js to be present in the project, while we had used a prebuilt version at the time.

That’s more or less the background. Now let’s get into the implementation. Tailwind – classnames are good, but can get complex Classnames are good Tailwind comes with a large set of pre-existing classes that you can use directly in your HTML and JavaScript. These classes enable consistency across the code. And they are entirely configurable: with the same classnames, we could easily brand our application. Therefore, with the help of Tailwind’s classnames, we created a consistent set of colors, spacing, fonts – essentially, all things CSS – and rolled out an easy-to-implement design system.  But Tailwind classes can get complex We wanted to simplify our usage of Tailwind’s classes. For this, we used techniques such as tagged template literals, interpolation, and conditions. We started with a long string of classes like the following:

CSS const className = 'stl-inline-flex stl-items-center stl-justify-center stl-rounded-full stl-h-10 stl-w-10 stl-bg-blue-100'; 1 const className = 'stl-inline-flex stl-items-center stl-justify-center stl-rounded-full stl-h-10 stl-w-10 stl-bg-blue-100';

But we soon realized that this was not easy to read. Additionally, it contained unnecessary noise, such as the prefix stl-, used to avoid clashes with other classes. So we enlisted the help of tagged template literals to remove the prefix from the string. We created an stl tag:

CSS const className = stl 'inline-flex items-center justify-center rounded-full h-10 w-10 bq-blue-100'; 1 const className = stl 'inline-flex items-center justify-center rounded-full h-10 w-10 bq-blue-100';

Finally, we wanted more readability. So we added:

Separate lines for more readability and grouping of common elements Interpolation with inline tagged template literals  Conditions for more powerful and adaptive styling

The result is an elegant piece of (CSS) code:

CSS const className = stl ' inline-flex items-center justify-center h-10 w-10 ${round && 'rounded-full'} ${iscool ? 'bg-blue-100' : 'bq-red-100'} ; 123456 const className = stl 'inline-flex items-center justify-centerh-10 w-10${round && 'rounded-full'}${iscool ? 'bg-blue-100' : 'bq-red-100'};

ESLint – effortlessly correcting human error Elegance is one thing. Correct is another. It’s easy to misspell classes, especially when there are many classes to initially learn about in Tailwind.  Here’s an example of what can go wrong: 

CSS cost className = stl 'felx space-between text-gray-200’; 1 cost className = stl 'felx space-between text-gray-200’;

Can you spot the errors?

Switching letters (felx for flex) Incomplete or non-existent classes (space-between) American vs British spelling (gray)

ESLint to the rescue – creating an ESLint plugin We needed to verify that the classes that people used were the correct ones. So we used ESLint to parse the code, analyze it, and report errors. We created an ESLint plugin to report errors on class names that didn’t exist. 

Here’s the central ESLint code that does the validation:

ESLint uses an abstract syntax tree (AST) that gives access to individual lines of code. The AST essentially converts the strings of the code into nodes, which you can parse as collections and elements. Here’s the breakdown of how ESLint parses the code. The whole expression is a node of type VariableDeclataion:

We want to parse the expression on the right side, the TaggedTemplateExpression. As you can see, there’s a callback that handles this kind of expression:   In the TaggedTemplateExpression callback, we collect all the strings in that template. For example:

The TemplateElement 

The Literals

Once the collecting is done, there’s another registered callback that loops through the collected class names and confirms whether they exist. It does this with the collection, validClassNames:  

That’s it. We knew right away that creating this validation plugin was the right thing to do, because we actually found a few misspellings in our system, as well as in the existing dashboard codebase! Proposing suggestions with our ESLint VisualStudio extension The last tool we created was an extension in Visual Studio Code. Using the same logic as in our plugin, ESLint suggests classes as a developer types. This intellisense keeps the developers from guessing or having to go to the Tailwind website to search for and find the correct classes. 

As you can see in the GIF, it not only proposes class names, it also displays the colors or useful icons for each suggestion. With Tailwind CSS and ESLint, we’ve been able to enforce our standards by improving the DX in implementing them. 

Peter Villani
  • Peter Villani
  • Writer & Editor

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK