-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
populateTypesenseIndex.js
72 lines (60 loc) · 1.99 KB
/
populateTypesenseIndex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* eslint-disable */
// Start Typesense server with `npm run typesenseServer`
// Then run `npm run populateTypesenseIndex` or `node populateTypesenseIndex.js`
const Typesense = require('typesense');
module.exports = (async () => {
const typesense = new Typesense.Client({
nodes: [
{
host: 'localhost',
port: '8108',
protocol: 'http',
},
],
apiKey: 'xyz',
});
const schema = {
name: 'books',
fields: [
{ name: 'title', type: 'string' },
{ name: 'authors', type: 'string[]', facet: true },
{ name: 'publication_year', type: 'int32', facet: true },
{ name: 'ratings_count', type: 'int32' },
{ name: 'average_rating', type: 'float', facet: true }
// Only fields that need to be searched / filtered by need to be specified in the collection's schema
// The documents you index can still contain other additional fields.
// These fields not mentioned in the schema, will be returned as is as part of the search results.
// { name: 'image_url', type: 'string' },
],
default_sorting_field: 'ratings_count',
};
console.log('Populating index in Typesense');
try {
await typesense.collections('books').delete();
console.log('Deleting existing collection: books');
} catch (error) {
// Do nothing
}
console.log('Creating schema: ');
console.log(JSON.stringify(schema, null, 2));
await typesense.collections().create(schema);
console.log('Adding records: ');
const books = require('./data/books.json');
try {
const returnData = await typesense
.collections('books')
.documents()
.import(books);
console.log(returnData);
console.log('Done indexing.');
const failedItems = returnData.filter(item => item.success === false);
if (failedItems.length > 0) {
throw new Error(
`Error indexing items ${JSON.stringify(failedItems, null, 2)}`
);
}
return returnData;
} catch (error) {
console.log(error);
}
})();