E-commerce industry
This topic describes how to use Alibaba Cloud OpenSearch to build a simple product search prototype for e-commerce scenarios to meet your business requirements for product search. A key business requirement when you build an e-commerce platform is the ability to search different attributes of product information by keyword and to filter the returned product list by category. A product search prototype built with Alibaba Cloud OpenSearch meets these project requirements well.
Prepare the environment
When you activate an Alibaba Cloud account and log on to the console for the first time, you are prompted to create an AccessKey pair before you can continue.
Creating and using applications depends on AccessKey parameters. The AccessKey parameters of the Alibaba Cloud account cannot be empty.
After you create AccessKey parameters for the Alibaba Cloud account, you can also create an AccessKey pair for a RAM user and use the RAM user for access. To grant the required access permissions to the RAM user, see Access authorization rules.
Basic architecture
The following figure shows the system architecture of the prototype:
Create an application
1. Log on to the OpenSearch console. In the left-side navigation pane, click Instance Management. On the Instance Management page, click Create Instance in the upper-left corner.
In the upper-left corner of the page, select OpenSearch Industry Algorithm Edition as the product edition, and select the destination region in the top navigation bar.
2. Select an application type.
This topic is based on an e-commerce scenario that involves multi-table relationship mapping. Therefore, select the Advanced application that supports simple multi-table JOIN logic type. For more information about application types, see OpenSearch application types.
3. Specify the application information.
The parameters used in this tutorial are as follows:
Set Product Version to Industry Algorithm Edition.
Set Product Type to Pay-as-you-go.
Set Region and Zone to China (Hangzhou).
Set Industry Type to E-commerce.
Set Cluster Preference to Exclusive Cluster - General-purpose.
Product type: The system supports subscription (prepaid) and pay-as-you-go (postpaid) billing. For more information about the differences, see Billing methods and pricing. Region and zone: OpenSearch is currently available in the following regions:
Chinese mainland and Hong Kong: China (Shenzhen), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hangzhou), China (Shanghai), and China (Hong Kong)
Asia Pacific: Singapore
Europe and Americas: Germany (Frankfurt) and US (Virginia)
Application name: The application name can contain digits, letters, and underscores (_), must start with a letter, and can be up to 30 characters in length. Note: The application name cannot be changed after the application is created. Application type: Advanced or Standard. Specifications: OpenSearch currently supports shared general-purpose, shared computing, shared storage, exclusive general-purpose, exclusive computing, and exclusive storage specifications. For more information, see Billing methods and pricing. Storage capacity and computing resources: Specify these based on your actual needs. Computing resources are estimated as follows: Number of LCUs = QPS × LCUs consumed by a single query. To determine the LCUs consumed by a single query, you can first purchase a shared general-purpose application and then check the LCU consumption of a single query by using the search test feature.
4. Configure the application.
Manually create an application schema: You can customize the application schema to create an application.
Create an application schema from a template: The system provides several commonly used templates by default. You can also save your own application schema as a template, and then use existing templates to quickly create new applications.
Upload a document to generate an application schema: You can upload an existing data file (only the JSON format is supported). The system automatically parses the file and creates an initial application schema. (Note that you need to redefine settings such as field types.)
Create an application schema from a data source: This method is suitable for scenarios in which data is synchronized from data sources such as RDS, MaxCompute (formerly ODPS), and PolarDB. You can quickly create an initial application schema based on the source table schema, which reduces manual work and the probability of errors. RDS is used as an example in this topic. The operations for other data sources are similar. For more information, see Configure data sources.
If you use Alibaba Cloud ODPS, RDS, or PolarDB, you can directly configure the corresponding data source in the OpenSearch console. Data is then automatically synchronized to OpenSearch, which is simple, convenient, and reliable. This topic uses RDS as an example and creates the application schema from a data source.
5. Connect to the data source.
Specify the database configuration: In the Connect to Database dialog box, enter the RDS Instance ID, Database Name, Username, and Password, and then click Connect.
6. Select the data source.
In the Select Data Source dialog box, click the RDS tab and set Select Database to opensearch (connected instance: rm-bp1pgu04tn0ia280e). In the Select Data Table section, add product_1 and price_detail_1 to the selected list, and then click OK.
7. Define the application schema.
The application schema uses the product table as the primary table and the product price table as the secondary table. The primary key pid of the product price table is associated with the foreign key id of the product table.
When you define the application schema, the primary table product_1 contains the following 15 fields:
category_name(category name, TEXT)image_url(LITERAL_ARRAY)description(product description, TEXT)brand_name(brand name, TEXT)thumbnail_url(LITERAL_ARRAY)title(product title, TEXT)is_onsale(INT)url(LITERAL)brand_id(LITERAL)series_id(LITERAL)sold_num(product sales volume, INT)category_id(INT)onsale_time(listing time, INT)price(DOUBLE)series_name(TEXT)
For each field, you can configure the primary key, field label, type, and external table join.
The secondary table price_detail_1 (data source: opensearch:price_detail_1) defines the following 4 fields:
discount_price, of the DOUBLE typepid, of the INT type, set as the primary keysale_price, of the DOUBLE typeact_price, of the DOUBLE type
8. Define the index schema.
Add the fields that need to be searched in the product table and the product price table to the index named "default". Then, you can search for products by using query=default:"keyword".
Set the industry to E-commerce and the template to General. The index field list contains the following index configurations:
default(default index): contains the fieldscategory_name,description,brand_name,title,create_by, andupdate_by. The analysis method is Industry - E-commerce General Analysis.category_name(category name index): The analysis method is Industry - E-commerce General Analysis.category_id: The analysis method is Keyword.series_name: The analysis method is Chinese - General Analysis.brand_name: The analysis method is Chinese - General Analysis.id: The analysis method is Keyword.title(title index): The analysis method is Industry - E-commerce General Analysis.seller_id: The analysis method is Keyword.brand_id: The analysis method is Keyword.series_id: The analysis method is Keyword.
Note: The analysis method directly affects search results. Select it with caution. For more information about how to select an analysis method, see the reference documentation.
9. Configure the data source.
Here, you can choose whether to enable automatic data synchronization. After it is enabled, data updates are automatically synchronized to OpenSearch. On the data source configuration page, the product_1 and price_detail_1 tables are both associated with the same RDS instance, and the Automatic Data Synchronization switch is turned on.
10. After the configuration is complete, click "Complete". On the application details page, you can see that the application is in the "Initializing" state.
Upload data
In the preceding example, RDS is used. During index building, full data import starts by default, and you can view the progress on the application details page. You can also call the OpenSearch API or SDK to manually upload data.
Test
After the data is uploaded, you can start experiencing search. You can perform queries in OpenSearch by using the API or SDK, or on the search test page built into the OpenSearch console. (For more information, see the API and SDK documentation.) This topic uses the search test page in the system as an example. For more information about search syntax, see Search API and query clause in the API developer guide. On the search test page, select the application test_han_indexes (offline application), enter query=title:'裙子' in the query bar, and set the config clause to start:0 to view the search results.
You can also use various custom features of OpenSearch to achieve a better search experience. For example, you can resolve issues such as few results being retrieved for long-tail queries, no results being retrieved for misspelled search terms, and no results being retrieved for Pinyin input. For more information, see Query analysis and Relevance in practice.
Configure query analysis: This section uses spelling correction as an example to configure query analysis.
Step 1: Create a query analysis intervention dictionary. 1.1 On the console homepage, choose Search Algorithm Center--Retrieval Configuration--Dictionary Management to go to the query analysis intervention dictionary page.
1.2 Click "Create" in the upper-right corner. In the Create Query Analysis Dictionary dialog box, set Name to dic_error, set Dictionary Type to Spelling Correction, and then click "Save". 1.3 In the dictionary list, click Manage Entries next to the dictionary that you created to go to the intervention dictionary page. On the entry management page, you can view the basic information of the dictionary (name, dictionary type, creation time, and number of entries), and add entries by clicking the Add Intervention Entry or Add Entries in Batches button. The entry list contains columns such as Query, Corrected Term, Intervention Type, Modified At, and Status.
1.4 Click Add Intervention Entry to configure your intervention entry. In the Add Intervention Entry dialog box, specify the following information:
Query: Enter the search term to be corrected, for example,
连衣群.Corrected Term: Enter the correct term, for example,
连衣裙.Intervention Type: Select Add or Block.
1.5 Click Save. The entry is added. You can view the intervention entry that you created in the intervention entry list. For example, the incorrect query 连衣群 is corrected to 连衣裙, the intervention type is "Add", and the status is "Effective". The Add Intervention Entry and Add Entries in Batches buttons are at the top of the intervention dictionary management page, and you can filter entries by using the Enter Query search box.
Step 2: In the left-side navigation pane of the OpenSearch console, choose Retrieval Configuration → Query Analysis Configuration to go to the query analysis page. Step 3: Click Create to add a rule that is not yet online, and select the dic_error intervention dictionary that you created. In the Add Rule dialog box, the target application is displayed as test_han_indexes (online application). Set the rule name to test_error (the name can contain digits, letters, and underscores, must start with a lowercase letter, and can be up to 16 characters in length). Set the index scope to title and the industry type to E-commerce. In the feature selection section, select Spelling Correction. Under dictionary usage, select Built-in System Dictionary, set the intervention dictionary to dic_error, and then click OK to create the rule.
Stop words: Filters out meaningless words in a query based on the built-in stop word dictionary. These are generally words that are used very frequently but do not affect query results, such as punctuation marks and modal particles. For example, for the query "奔跑吧!兄弟", after stop word processing, the punctuation mark "!" is not used for retrieval.
Spelling correction: Checks the user query string for spelling errors and provides correction suggestions. For definite spelling errors, the original query string is directly rewritten before retrieval. For possible spelling errors, the original query string is still used for retrieval. For example, the query 阿里爸爸 is rewritten to 阿里巴巴 by spelling correction before retrieval.
Term weight: Analyzes the importance of each term in a query and quantifies it as a weight. Terms with lower weights may not be used for retrieval. For example, for the query "开放搜索好不好", after term weight processing, all documents that contain "开放搜索" can be retrieved.
Synonyms: Expands the query string with synonyms based on the general synonym library and semantic model provided by the system to broaden retrieval. For example, if the original query is "KFC", after synonym processing, documents that contain "肯德基" or "KFC" are retrieved. (This works better when used together with the term weight feature.)
Named entity recognition: Named Entity Recognition (NER) is a feature in which the system identifies the intent of each semantic entity after the query is tokenized. Each semantic entity is tagged with a corresponding type label. Semantic entities whose type labels are of low importance may be omitted from the query, and semantic entities whose type labels are of high importance directly affect the training of the category prediction model. For example, for "耐克修身连衣裙", the NER results are "耐克/品牌/中", "修身/款式元素/低", and "连衣裙/品类/高".
Step 4: After the rule is created, you can click "Search Test" on the query analysis page to verify the effect. After creation, the rule is displayed in the query analysis configuration list: the query analysis name is test_error, the type is Custom, the target index is title, the industry is E-commerce, the included feature is Spelling Correction, and the Actions column provides Search Test, Configure, and Delete. On the search test page, select the corresponding index, set the parameter qp=test_error, enter the query title:'连衣群' (an intentional misspelling), and click Search. The system displays a message similar to "以下是查询 连衣裙 的结果,仍然搜: 连衣群". The actual query term is automatically corrected to (title:"连衣裙"), and products that match 连衣裙 are returned.
Step 5: After debugging is complete, return to the query analysis page, switch to the "Index View", and set the rule as the default query analysis. After the setting is complete, the new rule is displayed in the query analysis configuration list: the index name is title, the query analysis name is [Default]test_error (red indicates that the rule is not online), the Default column shows "Yes", the type is Custom, the included feature is Spelling Correction, and you can click Cancel Default Rule in the Actions column.
Configure sort expressions: Sort expressions allow you to customize how search results are sorted for an application. You can sort results by specifying an expression in the query request. For more information, see Search relevance configuration.
Step 1: On the application homepage, choose Sort Configuration → Policy Management to go to the search result sort management page.
Step 2: Click Create in the upper-right corner to add a new basic sort (rough sort).
In the basic information configuration, select the Target Application and its environment, enter a Policy Name (1 to 30 characters in length, starting with a letter, and containing uppercase and lowercase letters, digits, and underscores), set Type to Expression, and then click Next. In the sort configuration step, set Scoring Feature to static_bm250, set Weight to 1, and then click Complete. Basic sort (rough sort) has a significant impact on performance, so use the most representative fields whenever possible. This example configures scoring based on text score and document freshness.
Step 3: Add a new business sort (fine sort). On the basic information page of Create Policy, enter a Policy Name, set Scope to Business Sort, set Type to Expression, and then click Next to go to the sort configuration. In the sort expression editor, enter text_relevance(title), and then click Complete. This example configures product name relevance.
Step 4: Complete the configuration. On the Search Test page, select the index test_han_indexes, set the application type to Online Application, enter the query query=title:'裙子', set the config clause to start:0, and compare the search results returned by the two business sort policies side by side on the page to verify the effect of the fine sort configuration. The search test supports comparing the results of a regular query with the results of a query that uses a sort policy.
Configure drop-down suggestions: In e-commerce scenarios, you can use the drop-down suggestion feature of OpenSearch to reduce user input and help users find what they want as quickly as possible. For more information about how to configure drop-down suggestions, see Drop-down suggestions.
Configure category prediction: You can also use the category prediction feature to predict which category the user wants to query. For more information, see Category prediction.
Other common configurations:
In e-commerce scenarios, if multiple products of the same seller all have high document scores, they all appear at the top of the search results. This is bad for both result presentation and user experience. You can use the distinct clause to improve the diversity of results. For more information, see Aggregation clause - distinct.
The business also supports viewing results by price range, which requires the filter clause. For more information, see Filter clause - filter. The following sample code shows how to filter by the price field:
if(!lowPrice.equals("")){ queryElement.addFilter("price>=" + lowPrice); } if(!highPrice.equals("")){ queryElement.addFilter("price<=" + highPrice); }
Summary
You have now built a simple search prototype for e-commerce scenarios based on Alibaba Cloud OpenSearch. OpenSearch provides comprehensive search services and API operations, allowing you to quickly meet your business search requirements. This greatly reduces development work, improves the efficiency of developing search features, and reduces the workload and costs of system deployment and O&M associated with building a complex search engine platform. You can select various custom configurations and features of OpenSearch based on your business scenarios to achieve a better search experience.