Giter Site home page Giter Site logo

aishengyu / cognitive-search-static-web-apps-sample-ui Goto Github PK

View Code? Open in Web Editor NEW

This project forked from scale-tone/cognitive-search-static-web-apps-sample-ui

0.0 0.0 0.0 4.25 MB

A simple sample UI for your Azure Cognitive Search index. Built with React, TypeScript and Azure Static Web Apps

Home Page: https://red-desert-02fa5b603.2.azurestaticapps.net/

License: MIT License

TypeScript 98.46% CSS 0.17% HTML 1.38%

cognitive-search-static-web-apps-sample-ui's Introduction

Cognitive Search Static Web Apps sample

screenshot1

A simple sample UI for your Azure Cognitive Search index. Similar to this official sample, but is implemented as a Azure Static Web App and built with React and TypeScript. Implements the so called faceted search user experience, when the user first enters their search phrase and then narrows down search resuls with facets on the left sidebar.

Azure Static Web Apps CI/CD

The client part is a typical React-based SPA (Single-Page App) written in TypeScript with extensive use of MobX and Material-UI. And it doesn't have a backend as such, all requests to Cognitive Search REST API are transparently propagated through an Azure Functions Proxy, that appends the Cognitive Search api-key to each request - so the api-key is not exposed to the clients.

Queries made by user are also reflected in the browser's address bar. This serves three purposes: makes those links sharable, enables navigation history ("Back" and "Forward" buttons) and also helps you learn Cognitive Search REST API's query syntax.

List of search results supports infinite scrolling. If your documents have geo coordinates attached, then search results are also visualized with an Azure Maps control. Clicking on a search result produces the Details view, the Trascript tab of it highlights all occurences of your search phrase in the document and allows to navigate across them.

Please, also see this blog post.

Live demo

https://red-desert-02fa5b603.2.azurestaticapps.net

That deployment is pointed to the official Azure Cognitive Search Sample Data index (some sample hotel info in there), which is publicly available. You could point your deployment to that one as well, but normally you would like to build your own index as described here.

Config settings

This code requires the following settings to be provided. When running locally on your devbox, you configure them via your /api/local.settings.json file (you'll need to create this file first). After deploying to Azure you'll need to configure these values via your Static Web App's Configuration tab in Azure Portal.

  • SearchServiceName - the name of your Cognitive Search service instance, e.g. azs-playground.

  • SearchIndexName - the name of your search index, e.g. hotels. You can use your existing index if any, or you can create a sample index as described here.

  • SearchApiKey - your Cognitive Search query api-key. Find it on your Cognitive Search service's Keys tab in Azure Portal.

  • AzureMapSubscriptionKey - (optional) a subscription key for your Azure Maps account (Azure Maps is used for visualizing geolocation data). Please, get your own key as described here. If not specified, the map will not be shown.

  • CognitiveSearchKeyField - name of the field in your search index, that uniquely identifies a document. E.g. HotelId.

  • CognitiveSearchNameField - name of the field in your search index, that contains a short title of a document. E.g. HotelName. You can also put a comma-delimited list of field names here.

  • CognitiveSearchGeoLocationField - (optional) name of the field in your search index, that contains geo coordinates for each document. E.g. Location.

  • CognitiveSearchOtherFields - comma-separated list of other fields to be shown on search result cards. E.g. Tags,Description,Description_fr,Category,LastRenovationDate. If you include an array-type field (a field that contains an array of values, like the Tags field in the sample hotels index), it will be shown as a list of clickable chips.

  • CognitiveSearchFacetFields - comma-separated list of fields to be shown as facets on the left sidebar. Please, append a trailing star ('*') to the name of the field, if that field is an array-type field. E.g. Tags*,Rating,Category,ParkingIncluded,LastRenovationDate. NOTE: all fields mentioned here need to be facetable and filterable.

  • CognitiveSearchSuggesterName - (optional) name of the autocomplete suggester to be used. E.g. sg. Create and configure a suggester for your search index and put its name here - then the search query textbox will start showing suggestions as you type.

  • CognitiveSearchTranscriptFields - (optional) comma-separated list of fields to be shown on the Transcript tab of the Details dialog. E.g. HotelName,Description,Description_fr. The fields, that you specify in this setting need to be searchable, because they are also used to get the hit highlights. If not specified, that tab will simply show all string-type fields and get hit highlights from the search string.

How to run locally

As per prerequisites, you will need:

Clone this repo to your devbox, then in the /api folder create a local.settings.json file, which should look like this:

{
    "IsEncrypted": false,
    "Values": {
        "FUNCTIONS_WORKER_RUNTIME": "node",
        "AzureWebJobsFeatureFlags": "EnableProxies",

        "SearchServiceName": "azs-playground",
        "SearchIndexName": "hotels",
        "SearchApiKey": "your-search-api-key",
        "AzureMapSubscriptionKey": "your-azure-map-subscription-key",
        
        "CognitiveSearchKeyField":"HotelId",
        "CognitiveSearchNameField": "HotelName",
        "CognitiveSearchGeoLocationField": "Location",
        "CognitiveSearchOtherFields": "Tags,Description,Description_fr,Category",
        "CognitiveSearchFacetFields": "Tags*,Rating,Category,ParkingIncluded,LastRenovationDate",
        "CognitiveSearchTranscriptFields": "HotelName,Description,Description_fr",
        "CognitiveSearchSuggesterName": "sg"
    },
    "Host": {
        "CORS": "http://localhost:3000",
        "CORSCredentials": true
    }
}

Then type the following from the root folder:

npm install
npm run start-with-backend

The latter command also compiles and starts the /api project under the local 'http://localhost:7071/api' URL.

If a browser window doesn't open automatically, then navigate to http://localhost:3000.

How to deploy to Azure

  • Fork this repo (a fork is needed, because Static Web Apps deployment needs to have write access to the repo).

  • Make sure GitHub Actions are enabled for your newly forked repo:

  • Use this button:

    Deploy to Azure

Alternative deployment methods are described here. But then you'll need to manually configure the above-described Application Settings via your Static Web App's Configuration tab in Azure Portal. The tab should then look like this:

screenshot2

Authentication/Authorization

By default there will be no authentication configured for your Static Web App instance, so anyone could potentially access it. You can then explicitly configure authentication/authorization rules as described here. E.g. to force every user to authenticate with their Microsoft Account just replace anonymous with authenticated in this section of staticwebapp.config.json file. Note though, that authenticated is a built-in role, which refers to anybody anyhow authenticated. To restrict the list of allowed users further, you will need to define and assign your own custom roles and routes. Also, when using Microsoft Accounts, you might want to configure and use your own AAD application (instead of the global default one).

Implementation details

Thanks to MobX, this React app looks very much like a typical MVVM app. It has a hierarchy of state objects (aka viewmodels) and a corresponding hierarchy of pure (stateless) React components (aka views). These two hierarchies are welded together at the root level here. For example, here is the state object, that represents the list of search results, and here is its markup.

HTTP GET requests to Cognitive Search REST API are made by means of axios. As mentioned before, they do not go directly to Cognitive Search, but are transparently proxied via these Azure Proxies - this is where the api-key is being applied to them.

The list of facets and their possible values on the left sidebar is generated dynamically, based on CognitiveSearchFacetFields config value and results returned by Cognitive Search. The type of each faceted field (and the way it needs to be visualized) is also detected dynamically here. Multiple faceted field types is currently supported already, and more support is coming.

User's authN/authZ relies entirely on what Azure Static Web Apps offer today, and that in turn relies on what is known as EasyAuth server-directed login flow. That's why there're no any client-side JavaScript auth libraries and/or custom code for authenticating users. The only login-related code resides in this state object, and it only tries to fetch the current user's nickname, but for that code to work the authN/authZ rules need to be configured as explained here.

As usual with Azure Static Web Apps, deployment to Azure is done with GitHub Actions. There's a couple of workflows in this folder, that are currently being used for deploying this repo to demo environments. A good idea would be to remove them from your copy after cloning/forking (so that they don't annoy you with failed runs).

cognitive-search-static-web-apps-sample-ui's People

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.