liyugang
3 天以前 8c24730e9a52dc2c8933e8d41d2f9651de48a231
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { Client } from '@elastic/elasticsearch';
import * as fs from 'fs';
import * as mysql from 'mysql2';
import xlsx from "node-xlsx";
const INDEX_NAME = 'zlib_3';
 
const client = new Client({ node: 'http://localhost:9200' });
import * as rl from 'node:readline/promises'
 
async function createIndex() {
  try {
    if (await client.indices.exists({ index: INDEX_NAME })) { return; }
    await client.indices.create({
      index: INDEX_NAME,
      body: {
        mappings: {
          properties: {
            id: { type: 'keyword' },
            zid: { type: 'keyword' },
            ext: { type: 'text' },
            title: { type: 'text' },
            author: { type: 'text' },
            isbn: { type: 'text' },
            file: { type: 'text' },
            filesize: { type: 'long' },
            publisher: { type: 'text' },
            language: { type: 'text' },
            year: { type: 'text' },
            pages: { type: 'text' }
          },
        },
      }
    });
  } catch (e) {
    console.error(e);
  }
}
 
async function startImport() {
  const file = "E:\\annas_archive_meta__aacid__zlib3_records__20240809T171652Z--20240824T040729Z.jsonl.seekable";
  const rs = fs.createReadStream(file, 'utf-8');
  const readLine = rl.createInterface(rs);
  const books = [];
  let cnt = 0;
  let line = '';
  for await (const line of readLine) {
    const obj = JSON.parse(line);
    let filesize = obj.metadata.filesize_reported;
    if (!filesize) {
      let size = obj.metadata.annabookinfo?.response?.filesize;
      if (size) {
        filesize = parseInt(size);
      }
    }
    books.push({
      id: obj.aacid ?? '',
      zid: obj.metadata.zlibrary_id ?? 0,
      ext: obj.metadata?.extension ?? '',
      filesize: filesize ?? 0,
      file: (obj.metadata?.md5_reported ?? '') + '.' + (obj.metadata?.extension ?? ''),
      title: obj.metadata?.title ?? '',
      author: obj.metadata?.author ?? '',
      publisher: obj.metadata?.publisher ?? '',
      language: obj.metadata?.language ?? '',
      isbn: obj.metadata?.isbns?.[0] ?? '',
      year: obj.metadata?.year ?? '',
      pages: obj.metadata?.pages ?? ''
    });
    if (books.length % 100000 === 0) {
      const body = books.map(book => ([{ index: { _index: INDEX_NAME, _id: book.id } }, book])).flat();
      try {
        const response = await client.bulk({ body });
        console.log(response.errors);
        cnt += books.length;
      } catch (e) {
        console.error(e);
      }
      console.log(`已导入${cnt}条记录`);
      books.length = 0;
    }
  }
 
  readLine.on('close', async () => {
    const body = books.map(book => ([{ index: { _index: INDEX_NAME, _id: book.id } }, book])).flat();
    try {
      const response = await client.bulk({ body });
      console.log(response.errors);
      cnt += books.length;
    } catch (e) {
      console.error(e);
    }
    console.log(`已导入${cnt}条记录`);
    books.length = 0;
    connection.destroy();
    console.log('导入完成');
  });
}
// await createIndex();
// await startImport();
 
function getBookMap() {
  const bookMap = new Map();
  const bookLists = [
    // "c:/Users/lyg/Downloads/书单z-0-100w.xlsx",
    // "c:/Users/lyg/Downloads/书单z-100w-200w.xlsx",
    // "c:/Users/lyg/Downloads/书单z-200w-300w.xlsx",
    // "c:/Users/lyg/Downloads/书单z-300w-400w.xlsx",
    // "c:/Users/lyg/Downloads/书单z-400w-500w.xlsx",
    // "c:/Users/lyg/Downloads/书单z-500w-5027926.xlsx",
  ];
  bookLists.forEach(bookList => {
    const bookListData = xlsx.parse(bookList)[0].data;
    bookListData.shift();
    bookListData.forEach(book => {
      const isbn = book[1]?.trim() ?? '';
      const title = book[2]?.trim() ?? '';
      const author = book[3]?.trim() ?? '';
      bookMap.set(`${isbn}${title}${author}`, true);
    });
  });
  return bookMap;
}
 
async function exportBooks() {
  const hisBookMap = getBookMap();
  const bookMap = new Map();
  const responseQueue = [];
  const books = [];
  const response = await client.search({
    index: INDEX_NAME,
    scroll: '3h',
    size: 10000,
    _source: ['id', 'zid', 'language', 'title', 'author', 'publisher', 'isbn', 'ext', 'file'],
    query: {
      "bool": {
        "must": [
          {
            "wildcard": {
              isbn: "*"
            },
          },
          {
            "wildcard": {
              "language": "*",
            },
          },
          {
            "range": {
              "filesize": {
                "gt": 1024,
                "lt": 1024 * 1024 * 300
              }
            }
          }
        ],
        "must_not": [
          {
            "terms": {
              "language": ["english", "en", "chinese", "cn"]
            }
          },
        ]
      }
    }
  })
 
  responseQueue.push(response);
  let cnt = 0;
  let bookCnt = 0;
  let fileCnt = 1;
  while (responseQueue.length) {
    const body = responseQueue.shift()
 
    body.hits.hits.forEach(function (hit) {
      const bkId = `${hit._source.isbn}${hit._source.title}${hit._source.author}`;
      if (hisBookMap.has(bkId) || bookMap.has(bkId)) {
        return;
      }
      if (/^(\d{10,10}|\d{13,13})$/g.test(hit._source.isbn)) {
        bookMap.set(bkId, hit._source);
        bookCnt++;
        books.push(hit._source);
        if (books.length >= 500000) {
          saveBooks(books, fileCnt++);
          books.length = 0;
        }
      }
 
    });
    cnt += body.hits.hits.length;
 
    if (body.hits.total.value === cnt && books.length) {
      saveBooks(books, fileCnt++);
      break;
    }
 
    responseQueue.push(
      await client.scroll({
        scroll_id: body._scroll_id,
        scroll: '3h'
      })
    )
  }
 
}
 
function saveBooks(books, fileCnt) {
  let data = [['id', 'zid', '语种', '书名', '作者', '出版社', 'ISBN码', '文件格式', 'file']];
  data = data.concat(books.map(bk => [bk.id, bk.zid, bk.language, bk.title, bk.author, bk.publisher, bk.isbn, bk.ext, bk.file]));
  const buf = xlsx.build([{ "data": data }]);
  fs.writeFileSync(`zlib3_books_${fileCnt}[${books.length}].xlsx`, buf, 'binary');
}
 
exportBooks();